html部分
这里改了一下组件样式,如果不需要修改要修改样式直接使用van-uploader组件即可。
整体思路是用把上传的图片转为canvas然后在canvas上加水印图片或者文字,再把canvas转换成图片保存
有思路了就可以应用到后或者是pc的项目上了
<div v-if="imgBas64_1!=''" class="photo" style="margin-left: 0.2rem;">
<van-uploader :disabled="pageType!='add'" style="height: 100%;width: 100%;display: flex;justify-content: center;align-items: center;" :after-read="(file) => afterRead(2, file)" :deletable="true" >
<div class="PicturesImg" v-if="imgBas64_2" style="width: 1.82rem;height: 1.82rem;">
<p @click.stop="dPicture(1)"></p>
<img style="width: 100%;height: 100%; object-fit: cover" :src="imgBas64_2" alt="" />
</div>
<div v-else class="Pictures" style="width: 1.82rem; height: 1.82rem;display: flex;justify-content: center;align-items: center;">
<div></div>
</div>
</van-uploader>
</div>
js部分
afterRead 是上传图片的方法 dPicture是删除图片的方法(这个在这里就不说了) 上代码!
//上传文件的事件
afterRead(index,file) {
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
this.addWatermark(img, file,index);
};
img.src = e.target.result;
};
reader.readAsDataURL(file.file);
},
addWatermark(img, file,index) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// 设置 canvas 的大小与图片一致
canvas.width = img.width;
canvas.height = img.height;
// 绘制图片到 canvas 上
ctx.drawImage(img, 0, 0, img.width, img.height);
// 设置水印文本、样式和位置
const watermarkText = '水印水印水印水印';
const watermarkFontSize = 0.28;
const watermarkOpacity = 0.8;
// // 绘制背景图片
// 设置水印文本的样式
ctx.font = `${watermarkFontSize}rem Arial`;
ctx.fillStyle = `#fff`;
ctx.globalAlpha = watermarkOpacity;
// 绘制水印文本到 canvas 上
ctx.fillText(watermarkText, 100, 100);
ctx.fillText(watermarkText, 100, 200);
ctx.fillText(watermarkText, 100, 300);
// 创建新的Image对象
var icon = new Image();
// 设置图标图片的源地址
// icon.src =iconimg ;
// 确保图标图片加载完成后再绘制到Canvas上
icon.onload = function() {
// 在Canvas上绘制图标
// 参数分别为: 图像对象, 图像起始 cell 的 x 坐标, 图像起始 cell 的 y 坐标, 图像的宽度, 图像的高度, 在Canvas上的x坐标, 在Canvas上的y坐标, 在Canvas上的宽度, 在Canvas上的高度
ctx.drawImage(icon, 40, 60, 50, 50);
ctx.drawImage(icon, 40, 160, 50, 50);
ctx.drawImage(icon, 40, 260, 50, 50);
this.watermarkedImage = canvas.toDataURL('image/png');
if (index==1){
this.imgBas64_1 = this.watermarkedImage; //图片bess64
this.file_1=file
}else if(index==2){
this.imgBas64_2 = this.watermarkedImage; //图片bess64
this.file_2=file
}
imageCompress(file.file)
.then(({ dataURL, file }) => {
console.log({ dataURL, file },'');
// this.files = file;
})
.catch((errorCode) => {
if (errorCode === imageCompress.FILE_FORMAT_ERROR) {
return '不支持的文件格式';
}
if (errorCode === imageCompress.FILE_TOO_LARGE) {
return '文件尺寸太大';
}
if (errorCode === imageCompress.FILE_READ_ERROR) {
return '文件读取失败';
}
if (errorCode === imageCompress.COMPRESS_FAILED) {
return '压缩失败';
}
});
}.bind(this);
icon.src = iconimg; // 设置图标的源地址,这将触发图标的加载
},
大概就这么多,如果有其他需求可以再去优化!