先上效果图
1、图片添加文字

2、图片添加图片水印

1、图片添加文字水印
async init() {
let imgUrl =
"http://qysmjczto.hn-bkt.clouddn.com/37c1ed77-f934-4bd9-bc50-c7160decab5c.png";
const img = await this.loadImage(imgUrl);
const canvas = document.createElement("canvas");
const imgRatio = img.naturalWidth / img.naturalHeight;
const ctxWidth = 400;
const ctxHeight = ctxWidth / imgRatio;
canvas.width = ctxWidth;
canvas.height = ctxHeight;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, ctxWidth, ctxHeight);
const res = await this.watermark(canvas, "wf_cs");
},
loadImage(src) {
return new Promise((resolve, reject) => {
let img = new Image();
if (src.indexOf(src) === 0) {
img.crossOrigin = "*";
}
img.src = src;
img.onload = () => {
resolve(img);
};
img.onerror = () => {
reject(new Error("图片解析失败"));
};
});
},
watermark(canvas, text) {
return new Promise((resolve, reject) => {
let ctx = canvas.getContext("2d");
ctx.font = "22px";
ctx.fillStyle = "blue";
ctx.textAlign = "right";
ctx.fillText(text, canvas.width - 20, canvas.height - 30);
resolve(canvas.toDataURL("image/png", 1));
});
}
2、添加图片水印
- 方法实现原理为canvas上进行图片的叠加
- 因为需要水印透明,因此建议先生成水印再生成地图,避免把底图也透明了
- 考虑到水印一般会出现多个,因此抽离出addImageWatermark方法,该方法控制水印的位置大小等,实际开发请根据图片的大小自行计算传入的x y值
async init() {
const img = await this.loadImage(require("../../assets/canvas.png"));
const img2 = await this.loadImage(require("../../assets/test.png"));
const canvas = document.createElement("canvas");
const imgRatio = img2.naturalWidth / img2.naturalHeight;
const ctxWidth = 400;
const ctxHeight = ctxWidth / imgRatio;
canvas.width = ctxWidth;
canvas.height = ctxHeight;
const ctx = canvas.getContext("2d");
for (var i = 0; i < 5; i++) {
this.addImageWatermark(ctx, img, 40 * (i + 1) + 5, 80, 40, 40);
}
await this.watermark(canvas, "这是文字水印");
ctx.drawImage(img2, 0, 0, ctxWidth, ctxHeight);
this.newImage = canvas.toDataURL("image/jpg", 1);
},
async addImageWatermark(ctx, img, x, y, width, height) {
ctx.drawImage(img, x, y, width, height);
let imgData = ctx.getImageData(x, y, width, height);
for (var i = 0, len = imgData.data.length; i < len; i += 4) {
imgData.data[i + 3] = imgData.data[i + 3] * 0.1;
}
ctx.putImageData(imgData, x, y);
},
loadImage(src) {
return new Promise((resolve, reject) => {
let img = new Image();
if (src.indexOf(src) === 0) {
img.crossOrigin = "*";
}
img.src = src;
img.onload = () => {
resolve(img);
};
img.onerror = () => {
reject(new Error("图片解析失败"));
};
});
},
watermark(canvas, text) {
return new Promise((resolve, reject) => {
let ctx = canvas.getContext("2d");
ctx.font = "22px";
ctx.fillStyle = "blue";
ctx.textAlign = "right";
ctx.fillText(text, canvas.width - 20, canvas.height - 30);
ctx.font = "12px 宋体";
ctx.fillStyle = "red";
ctx.textAlign = "right";
let date = new Date().getTime();
ctx.fillText(date, canvas.width - 20, canvas.height - 20);
resolve(canvas.toDataURL("image/png", 1));
});
}