切图也有两年多了,不过一直没有使用过canvas
,最近有个上传图片增加水印的需求,正好可以试试canvas
加水印。
1、文字水印合成
主要操作流程如下:
- 将需要添加水印的图片绘制到 canvas 上
- 将水印绘制到 canvas 上
- 将 canvas 的内容导出为图片
1.1 将图片绘制canvas上
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const img = new Image(); // 开启跨域 img.crossOrigin = 'anonymous'; img.src = "https://xypecho.github.io/2019/06/24/%E6%AF%95%E4%B8%9A%E6%95%B4%E6%95%B4%E4%B8%89%E5%B9%B4%E4%BA%86/TIM%E5%9B%BE%E7%89%8720190624205011.png"; img.onload = function () { // canvas自适应图片的宽高 canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0); // 需要添加水印的图片绘制完成后调用方法watermarkedDataURL来绘制水印,第一个参数是canvas对象,第二个是文字水印 watermarkedDataURL(canvas, "It's Mine!"); }
|
1.2 将水印图片绘制到刚刚的canvas上
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| function watermarkedDataURL(canvas, text) { const tempCanvas = document.createElement('canvas'); const tempCtx = tempCanvas.getContext('2d'); let cw, ch; cw = tempCanvas.width = canvas.width; ch = tempCanvas.height = canvas.height; tempCtx.drawImage(canvas, 0, 0); tempCtx.font = "24px verdana"; const textWidth = tempCtx.measureText(text).width; tempCtx.globalAlpha = .50; tempCtx.fillStyle = 'white' tempCtx.fillText(text, cw - textWidth - 10, ch - 20); tempCtx.fillStyle = 'black' tempCtx.fillText(text, cw - textWidth - 10 + 2, ch - 20 + 2); document.body.appendChild(tempCanvas); return (tempCanvas.toDataURL()); }
|
点击这里看文字水印demo
2、图片水印合成
最开始的操作都是一样的,将要加水印的图片绘制到canvas上,然后
1 2 3 4 5 6 7 8
| function watermarkedDataURL(canvas) { const tempImg = new Image(); tempImg.crossOrigin = 'anonymous'; tempImg.src = "https://xypecho.github.io/test/watermark/watermark.png"; tempImg.onload = function () { ctx.drawImage(tempImg, 1, 1, tempImg.width / 2, tempImg.height / 2) } }
|
点击这里看图片水印demo