wxml
<view class="canvas-box">
<canvas style="width: 375px;height: 667px;position:fixed;top:9999px" canvas-id="mycanvas" />
</view>
js
// 选择图片
chooseImage: function (e) {
console.log('选择图片chooseImage')
var that = this;
wx.chooseImage({
count: that.data.count, // 默认9
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
that.addTimeWatermark(res.tempFilePaths[0])
},
})
},
// 添加时间水印
addTimeWatermark: function (imagePath) {
var that = this
console.log('addTimeWatermark=' + imagePath)
var ctx = wx.createCanvasContext('mycanvas');
this.roundRectColor(ctx, 0, 30, 375, 620, 16);
ctx.drawImage(imagePath, 15, 120, 344, 400);
ctx.save();
// 设置水印文字
const time = app.util.formatTime()
console.log('time=' + time)
ctx.beginPath(); //开始绘制
ctx.setFontSize(22);
ctx.setFillStyle('#DC3545')
ctx.fillText(time, 15, 580); // 根据实际情况调整位置
ctx.draw();
//将生成好的图片保存到本地,需要延迟一会,绘制期间耗时
setTimeout(function () {
wx.canvasToTempFilePath({
canvasId: 'mycanvas',
success: function (res) {
var tempFilePath = res.tempFilePath;
console.log('imagePath=' + tempFilePath)
that.data.images.push(tempFilePath);
console.log(that.data.images)
that.setData({
imagePath: tempFilePath,
});
},
fail: function (res) {
console.log(res);
}
});
}, 200);
},
roundRectColor: function (context, x, y, w, h, r) { //绘制圆角矩形(纯色填充)
context.save();
context.setFillStyle("#FFFFFF"); //小框
context.setStrokeStyle('#FFFFFF') //大框
// context.setLineJoin('round'); //交点设置成圆角
context.setLineWidth(r);
context.strokeRect(x + r / 2, y + r / 2, w - r, h - r);
context.fillRect(x + r, y + r, w - r * 2, h - r);
context.stroke();
context.closePath();
},