基于uniapp实现微信小程序图片上传添加水印
html
代码如下(示例):
<canvas canvas-id="firstCanvas" class="canvas" :style="{'width': w+'px','height':h+'px','left':(-w*2)+'px'}"></canvas>
w:图片的宽
h:图片德高
left:把标签定为fixed定位 因为我这里是不需要显示canvas的水印添加成功还是要上传到服务器的 看自己需求,v-show、v-if的会导致canvas无效水印添加不上,所以只能用left把它挪到视图看不见的地方
js
代码如下(示例):
let that = this
wx.getImageInfo({
src:path,
success:function(res){
uni.showLoading({
title: '上传中'
});
var width = res.width, height = res.height;
that.w=width;
that.h=height;
//获取当前时间
let newDate = new Date();
let year = newDate.getFullYear() //年
let month = newDate.getMonth() + 1 //月
let day = newDate.getDate() //日
var hour = newDate.getHours()
var minute = newDate.getMinutes()<10?'0'+newDate.getMinutes():newDate.getMinutes()
var second = newDate.getSeconds()<10?'0'+newDate.getSeconds():newDate.getSeconds()
let roleNameInfo = year + '-' + month + '-' + day + ' '+hour+':'+minute+':' +second
let location=that.addr
//创建canvas
const ctx = wx.createCanvasContext('firstCanvas',that);
ctx.drawImage(path, 0, 0, width, height); //先画出图片
//将声明的时间放入canvas
ctx.setFontSize(30) //注意:设置文字大小必须放在填充文字之前,否则不生效
ctx.font = 'bold 50px 微软雅黑'
ctx.strokeStyle = "black";
ctx.strokeText(roleNameInfo, 60, height - 40);
ctx.strokeText(location, 60, height - 100);
ctx.setFillStyle('white');
ctx.fillText(roleNameInfo, 60, height - 40);
ctx.fillText(location, 60, height - 100);
ctx.strokeText(name, 60, 100);
ctx.fillText(name, 60,100);
ctx.draw(false, () => {//开始制作
setTimeout(() => {//使用定时是因为制作水印需要时间,设置定时才不会出bug
wx.canvasToTempFilePath({//将画布中内容转成图片,即水印与图片合成
canvasId: 'firstCanvas',
// fileType:'jpg',
success: (res) => {
console.log(res.tempFilePath) 返回的新图片链接 可以用作于上传传输给后端
},
fail:(e)=>{
console.log("eeeeeeeeeee",e)
}
},that)
}, 50)
})
//end
},
})
path为 wx.chooseImage返回的临时图片链接
总结
自己可以看自己的需求 我的需求是要添加实时的日期和地址,当用户选择拍摄时才会添加水印 从相册选择是不会添加水印