|
@@ -38,11 +38,8 @@ export const imgToCanvas = async (url: string) => {
|
|
|
|
|
|
export const addWatermark = async (canvas: any) => {
|
|
export const addWatermark = async (canvas: any) => {
|
|
try {
|
|
try {
|
|
- const ctx = canvas.getContext('2d');
|
|
|
|
- // ctx.fillStyle = '#fff'
|
|
|
|
const img = document.createElement('img');
|
|
const img = document.createElement('img');
|
|
img.setAttribute('crossOrigin', 'anonymous');
|
|
img.setAttribute('crossOrigin', 'anonymous');
|
|
-
|
|
|
|
// 为了处理base64 和 连接加载不同的
|
|
// 为了处理base64 和 连接加载不同的
|
|
if (
|
|
if (
|
|
imgList &&
|
|
imgList &&
|
|
@@ -53,25 +50,25 @@ export const addWatermark = async (canvas: any) => {
|
|
} else {
|
|
} else {
|
|
img.src = imgList;
|
|
img.src = imgList;
|
|
}
|
|
}
|
|
-
|
|
|
|
// 防止跨域引起的 Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
|
|
// 防止跨域引起的 Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
|
|
await new Promise(resolve => (img.onload = resolve));
|
|
await new Promise(resolve => (img.onload = resolve));
|
|
-
|
|
|
|
- // 创建canvas DOM元素,并设置其宽高和图片一样
|
|
|
|
|
|
+ // 容器
|
|
const water = document.createElement('canvas');
|
|
const water = document.createElement('canvas');
|
|
- water.width = 280;
|
|
|
|
- water.height = 220;
|
|
|
|
- // 小水印画布大小
|
|
|
|
-
|
|
|
|
- // 第一层
|
|
|
|
|
|
+ water.width = canvas.width
|
|
|
|
+ water.height = canvas.height
|
|
const waterCtx = water.getContext('2d') as CanvasRenderingContext2D;
|
|
const waterCtx = water.getContext('2d') as CanvasRenderingContext2D;
|
|
- waterCtx.clearRect(0, 0, water.width, water.height);
|
|
|
|
- // 小水印中文字偏转角度
|
|
|
|
- waterCtx.drawImage(img, 80, 80);
|
|
|
|
- const pat = ctx.createPattern(water, 'repeat');
|
|
|
|
- ctx.fillStyle = pat;
|
|
|
|
- ctx.fillRect(0, 0, canvas.width, canvas.height);
|
|
|
|
- return canvas;
|
|
|
|
|
|
+ waterCtx.drawImage(canvas, 0, 0);
|
|
|
|
+ // 水印图片
|
|
|
|
+ const imgCanvas = document.createElement('canvas');
|
|
|
|
+ imgCanvas.width = 280
|
|
|
|
+ imgCanvas.height = 220;
|
|
|
|
+ const imgCtx = imgCanvas.getContext('2d') as CanvasRenderingContext2D;
|
|
|
|
+ imgCtx.drawImage(img, 80, 80);
|
|
|
|
+ // 添加水印
|
|
|
|
+ const pat = waterCtx.createPattern(imgCanvas, 'repeat')!;
|
|
|
|
+ waterCtx.fillStyle = pat;
|
|
|
|
+ waterCtx.fillRect(0, 0, water.width, water.height);
|
|
|
|
+ return water;
|
|
} catch (e) {
|
|
} catch (e) {
|
|
console.log(e);
|
|
console.log(e);
|
|
}
|
|
}
|