1、创建画布
var context = uni.createCanvasContext('Canvas')
2、获取本地图片
uni.chooseImage({
count: 1,
success: (res) => {
var file = res.tempFilePaths[0];
const tempFiles = res.tempFiles[0]
})
})
3、获取图片信息----添加水印
uni.getImageInfo({
src: res.tempFilePaths[0],
success: function(image) {
_self.width = image.width + 'px'
_self.height = image.height + 'px'
setTimeout(function() {
context.width = _self.width;
context.height = _self.height;
context.fillRect(0, 0, _self.width, _self.height);
// 将图片src放到cancas内,宽高为图片大小
context.drawImage(res.tempFilePaths[0], 0, 0, image.width, image.height)
context.rotate(45 * Math.PI / 180);
for (let i = 0; i <= 50; i++) {
context.beginPath();
context.setFontSize(50);
context.setFillStyle("rgba(169,169,169,0.4)");
context.fillText("我是水印", 0, i * 170);
for (let j = 0; j <= 50; j++) {
context.beginPath();
context.setFontSize(50);
context.setFillStyle("rgba(169,169,169,0.4)");
context.fillText("我是水印", j * 340, i * 170);
}
}
for (let i = 0; i < 50; i++) {
context.beginPath();
context.setFontSize(50);
context.setFillStyle("rgba(169,169,169,0.4)");
context.fillText("我是水印", 0, -170 * i);
for (let j = 1; j < 50; j++) {
context.beginPath();
context.setFontSize(50);
context.setFillStyle("rgba(169,169,169,0.4)");
context.fillText("我是水印", 340 * j, -170 * i);
}
}
context.rotate(-45 * Math.PI / 180);
uni.showLoading({
title: '上传中...',
})
context.draw(false, () => {
setTimeout(() => {
uni.canvasToTempFilePath({
canvasId: "Canvas",
fileType: 'jpg',
success: (path) => {
//压缩
uni.compressImage({
src: path.tempFilePath,
quality: 20,
success: res => {}
})
}
})
}, 500)
})
}, 1000)
}
})
1、 _self 是我全局定义的this,你们用的时候请自己全局定义一下this
2、如果没有显示请根据自己图片像素设置一下水印字体大小和距离