美文网首页
canvas-图片添加水印

canvas-图片添加水印

作者: 汀上 | 来源:发表于2019-12-11 18:11 被阅读0次
//传的参数可以自己配置
_picZ({
        url = "",
        textAlign = "left",
        textBaseline = "top",
        font = "12px Microsoft Yahei",
        fillStyle = "rgba(6, 6, 6, .5)",
        content = "",
        cb = null
    } = {}) {
        const img = new Image();
        img.src = url;
        img.crossOrigin = "anonymous";
        img.onload = function () {
            const canvas = document.createElement("canvas");
            let _ix = img.width;
            let _iy = img.height;
            canvas.width = _ix;
            canvas.height = _iy;
            const ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0);
            ctx.textAlign = textAlign;
            ctx.textBaseline = textBaseline;
            ctx.font = font;
            ctx.fillStyle = fillStyle;
            ctx.translate(0, 0);
            ctx.rotate((Math.PI / 180) * 15);  //旋转角度
            //密度可以自己定
            for (let i = 0; i < _iy / 120; i++) {  
                for (let j = 0; j < _ix / 50; j++) {
                    ctx.fillText(content, i * 120, j * 50, _ix);
                }
            }
            const base64Url = canvas.toDataURL();
            cb && cb(base64Url);
        };
    }

调用

_picZ({
          url: URL.createObjectURL(file), //这里传的file是上传的图片文件
          content: "添加水印文案",
          cb: base64Url => {
            console.log(base64Url) //转换完成的base64格式图片
          }
      });

效果(二维码乱找的不要扫):


1.PNG

相关文章

网友评论

      本文标题:canvas-图片添加水印

      本文链接:https://www.haomeiwen.com/subject/mnlagctx.html