微信小程序使用wx.chooseMedia拍摄或从手机相册中选择图片并添加水印,
代码如下:
// WXML代码:
<canvas canvas-id="watermarkCanvas" style="width: {{canvasWidth}}px; height: {{canvasHeight}}px;"></canvas>
<button bindtap="addWatermark">选择图片并添加水印</button>
// js代码:
data: {
canvasWidth: 0,
canvasHeight: 0
},
addWatermark() {
// 是否清空页面上的视觉效果
this.setData({
canvasWidth: 0,
canvasHeight: 0
});
wx.chooseMedia({
count: 1,
mediaType: ['image'],
sourceType: ['album', 'camera'],
success: (res) => {
const tempFilePath = res.tempFiles[0].tempFilePath;
wx.getImageInfo({
src: tempFilePath,
success: (imageInfo) => {
// 获取屏幕宽度
const systemInfo = wx.getSystemInfoSync();
const screenWidth = systemInfo.screenWidth;
// 计算图片在canvas中的大小,保持原始宽高比
const scale = screenWidth / imageInfo.width;
const canvasWidth = screenWidth;
const canvasHeight = imageInfo.height * scale;
// 更新 canvas 尺寸
this.setData({
canvasWidth: canvasWidth,
canvasHeight: canvasHeight
}, () => {
// 在 setData 回调中创建 canvas 上下文,确保尺寸已更新
const ctx = wx.createCanvasContext('watermarkCanvas');
// 清空 canvas
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// 绘制原图,铺满整个canvas
ctx.drawImage(tempFilePath, 0, 0, canvasWidth, canvasHeight);
// 设置水印样式
ctx.setFontSize(16); // 固定字体大小为16px
ctx.setFillStyle('rgba(255, 255, 255, 0.5)');
ctx.setShadow(2, 2, 2, 'rgba(0, 0, 0, 0.5)');
ctx.rotate(-Math.PI / 6);
// 添加水印文字
const watermarkText = '我的水印';
const textWidth = ctx.measureText(watermarkText).width;
const xGap = textWidth * 2; // 增加横向间距
const yGap = 48; // 增加纵向间距
// 确保水印覆盖整个canvas,包括旋转后的边角
const diagonal = Math.sqrt(canvasWidth * canvasWidth + canvasHeight * canvasHeight);
for (let y = -diagonal; y < diagonal * 2; y += yGap) {
const rowOffset = ((y / yGap) % 2) * (xGap / 2); // 偶数行错开半个宽度
for (let x = -diagonal - rowOffset; x < diagonal * 2; x += xGap) {
ctx.fillText(watermarkText, x, y);
}
}
ctx.draw(false, () => {
wx.canvasToTempFilePath({
canvasId: 'watermarkCanvas',
success: (res) => {
const watermarkedImagePath = res.tempFilePath;
console.log(watermarkedImagePath, 'watermarkedImagePath')
// 上传图片的方法
this.uploadImage(watermarkedImagePath);
},
fail: (error) => {
console.error('Canvas to image failed:', error);
}
});
});
});
},
fail: (error) => {
console.error('Get image info failed:', error);
}
});
},
fail: (error) => {
console.error('Choose media failed:', error);
}
});
},