我不理解,我麻了,为什么会这样呢?为什么会有这样的要求?算了还是封装起来吧
一步步来吧,首先需要在页面创建一个canvas用来给图片添加水印
<canvas id="myCanvas" type="2d" style="width: {{canvasWidth}}px; height: {{canvasHeight}}px;position: absolute; left: -9999px;" />
然后就可以开始给图片添加水印了
previewImages(e) {
wx.showLoading({
title: '请稍等',
mask: true
})
const imageList = e.currentTarget.dataset.list; //图片列表
const index = e.currentTarget.dataset.index;//图片下标
Promise.all(imageList.map(item => this.addWaterMark(item.avatar || item.filePath)))
.then(urlList => {
wx.previewImage({
current: urlList[index],
urls: urlList,
})
}).catch(error => {
wx.hideLoading();
})
},
// 使用canvas绘制水印图片
addWaterMark(localImgUrl) {
let that = this
return new Promise((resolve, reject) => {
wx.getImageInfo({
src: localImgUrl,
success(res) {
const imgWidth = res.width
const imgHeight = res.height
const query = wx.createSelectorQuery().in(that)//in(this),不加有时获取不到对应的DOM元素
query.select('#myCanvas').fields({ node: true, size: true })
query.exec((res) => {
const canvas = res[0].node
const canvasWidth = res[0].width
const canvasHeight = res[0].height
const ctx = canvas.getContext('2d')
// 画布大小初始化
const dpr = wx.getSystemInfoSync().pixelRatio
canvas.width = canvasWidth * dpr
canvas.height = canvasHeight * dpr
ctx.scale(dpr, dpr)
const img = canvas.createImage()
img.src = localImgUrl
img.onload = () => {
// 清空画布内容
ctx.clearRect(0, 0, canvasWidth, canvasHeight)
ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight)
// 设置水印样式
let fontSize = 20; //水印字体大小
let maskText = '我的水印'; //水印文字
let fontColor = "#559FFE"; //水印颜色
let lineHeight = 80; //水印文字行高
let textWidth = 100; //水印文字宽度
let diagonalLength = canvasHeight > canvasWidth ? canvasHeight * 2 : canvasWidth; //选取最长边
// console.log(diagonalLength);
// 保证水印文字范围是矩形最长边的2倍
ctx.save();
ctx.beginPath();
ctx.translate(canvasWidth / 2, -diagonalLength);
ctx.rotate(45 * Math.PI / 180); //设置文字的旋转角度,角度为45°;
// 横向循环次数
let crossTime = Math.ceil(diagonalLength * 2 / textWidth);
// 竖向循环次数
let verticalTime = Math.ceil(diagonalLength * 2 / lineHeight);
for (let j = 0; j < verticalTime; j++) { //纵向循环
ctx.font = `${fontSize}px serif`;
ctx.fillStyle = fontColor
ctx.fillText(maskText, 0, lineHeight * j);
for (let i = 1; i < crossTime; i++) { //横向循环
ctx.font = `${fontSize}px serif`;
ctx.fillStyle = fontColor
ctx.fillText(maskText, textWidth * i, lineHeight * j);
}
};
ctx.closePath()
ctx.restore()
// 导出图片并将图片路径返回
wx.canvasToTempFilePath({
canvas,
success: function(res) {
// console.log(res.tempFilePath);
resolve(res.tempFilePath);
},
fail: function(err) {
reject(err);
},
})
}
})
},
fail(err){
console.log(err)
}
})
})
},
有一点要提醒小伙伴,如果你和我一样是图片列表的话一定记得要在给图片绘制水印之前清除画布内容,不然你会看到之前绘制的图片出现在下一张里:
ctx.clearRect(0, 0, canvasWidth, canvasHeight)
还是看一下效果吧
完结~~撒花~~~