从文件读取图片的url
function loadFileUrl(file) {
return new Promise((resolve, reject) => {
const a = new FileReader();
a.onload = function (res) {
if (res && res.target) {
resolve(res.target.result);
} else {
reject(new Error('读取文件url失败'));
}
};
a.readAsDataURL(file);
});
}
加载画布
function loadFileCanvas(file) {
return new Promise((resolve, reject) => {
loadFileUrl(file).then(url => {
const img = new Image();
img.onload = function () {
if (this.complete) {
const canvas = document.createElement('canvas');
canvas.height = img.height;
canvas.width = img.width;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
resolve({canvas, ctx, img});
} else {
reject(new Error('水印添加,文件加载失败'));
}
};
img.src = url;
}).catch(reject);
});
}
添加水印
new Promise((resolve, reject) => {
loadFileCanvas(file).then(({canvas, ctx}) => {
// 为上传图片添加水印效果
// 绘制水印
ctx.textAlign = 'center';
ctx.fillStyle = '#223355';// 配置字体颜色
ctx.font = '12px normal PingFangSC-Regular';
ctx.fillText('水印内容', 40, 40); // 后面两个参数分别为x、y偏移量
// 输出文件
canvas.toBlob(blob => {
if (!blob) {
reject(new Error('添加水印异常'));
return;
}
const waterMarkFile = new File([blob], file.name, {
type: file.type,
lastModified: file.lastModified,
});
resolve(waterMarkFile);
});
});
});