做园区巡检需求时,需要巡检打卡拍照上传功能,并且在照片上添加当前时间的水印
- 创建canvas
- 拍照后拿着图片画到canvas上
- 同时获取当前时间也画到canvas上,
- 再将canvas生成base64的url
- 拿着合成的图片url进行下面的逻辑
- 上代码
function addWatermark(imagePath,mark,calback) {
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDay();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
let str = year +'年'+ month+'月'+ day +'日'
let str2 = hours + ":" + minutes + ":" + seconds
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
// 创建一个新的Image对象,用于加载原始图片
let image = new Image();
image.src = imagePath;
// 在图片加载完成后执行下面的代码
image.onload = function() {
canvas.width = image.width;
canvas.height = image.height;
// 将原始图片绘制到canvas上
context.drawImage(image, 0, 0);
let size = image.width/20
//将水印文本添加上
context.font = size+ "px Arial";
context.fillStyle = "#FF0000"; // 设置填充颜色为红色
context.fillText(str + ' '+ str2, 20, size)
if(mark){
context.fillText(mark, 20, size*2)
}
// 将带有水印的图片转换为base64格式
let watermarkedImage = canvas.toDataURL();
calback&&calback(watermarkedImage)
};
}
- 效果
![在这里插入图片描述](https://img-blog.csdnimg.cn/f7ce346d14f74aac9ff356c596ff6e03.png)