1.需要先在view中增加一个canvas
<!-- 设置canvas用于添加水印 -->
<canvas id="canvas-clipper" canvas-id="canvas-clipper" type="2d"
:style="{width: canvasSiz.width+'px',height: canvasSiz.height+'px',position: 'absolute',left:'-500000px',top: '-500000px'}" />
2.这里的两个参数只需要关注第一个path就行了,为相册选择的图片地址或者拍照得到的图片地址
// 增加水印并保存到相册
watermark(path, name) {
// 获取图片信息
uni.getImageInfo({
src: path,
success: function(image) {
_this.canvasSiz.width = image.width;
_this.canvasSiz.height = image.height;
//担心尺寸重置后还没生效,故做延迟
setTimeout(() => {
let ctx = uni.createCanvasContext('canvas-clipper', _this);
ctx.drawImage(
path,
0,
0,
image.width,
image.height
);
// 设置文字水印
ctx.setFillStyle('white');
ctx.setFontSize(30);
ctx.fillText('抄表日期:', 20, 100);
//再来加个时间水印
var date = new Date();
//这里用了uview的js如果不适配需要自行修改
var time = _this.$u.timeFormat(date, 'yyyy年mm月dd日 hh时MM分ss秒')
ctx.setFontSize(30);
ctx.fillText(time, 20, 140);
ctx.draw(false, () => {
// 导出图片
uni.canvasToTempFilePath({
destWidth: image.width,
destHeight: image.height,
canvasId: 'canvas-clipper',
fileType: 'png',
success: function(res) {
_this.savePhoto(res.tempFilePath, name);
}
},
//这个_this是当前页this在onload里面赋值的
_this
);
});
}, 500)
}
});
},
//保存图片到相册,方便核查
savePhoto(path, name) {
//保存到相册
uni.saveImageToPhotosAlbum({
filePath: path,
success: () => {
uni.showToast({
title: '已保存至相册',
duration: 2000
});
}
});
},
3._this的声明
![](https://img.haomeiwen.com/i20117723/2b95a1a7dc4f22e4.png)
![](https://img.haomeiwen.com/i20117723/7a8986b2ce1f610f.png)
4.效果图
![](https://img.haomeiwen.com/i20117723/aae85e5f388bb6e7.png)
网友评论