微信小程序预览图片canvas添加水印

文章讲述了如何在微信小程序中通过canvas元素和相关API给图片添加水印的过程,包括创建canvas,获取图片信息,绘制水印文字,以及导出处理后的图片。代码示例详细展示了图片列表中每张图片添加水印的实现方法,并强调了清除画布内容以避免图片叠加的问题。
摘要由CSDN通过智能技术生成

我不理解,我麻了,为什么会这样呢?为什么会有这样的要求?算了还是封装起来吧

一步步来吧,首先需要在页面创建一个canvas用来给图片添加水印

<canvas id="myCanvas" type="2d" style="width: {{canvasWidth}}px; height: {{canvasHeight}}px;position: absolute; left: -9999px;" />

然后就可以开始给图片添加水印了

  previewImages(e) {
        wx.showLoading({
            title: '请稍等',
            mask: true
        })
        const imageList = e.currentTarget.dataset.list; //图片列表
        const index = e.currentTarget.dataset.index;//图片下标
        Promise.all(imageList.map(item => this.addWaterMark(item.avatar || item.filePath)))
          .then(urlList => {
            wx.previewImage({
              current: urlList[index],
              urls: urlList,
            })
          }).catch(error => {
            wx.hideLoading();
    })
    },
  // 使用canvas绘制水印图片
  addWaterMark(localImgUrl) {
      let that = this
    return new Promise((resolve, reject) => {
        wx.getImageInfo({
            src: localImgUrl,
            success(res) {
              const imgWidth = res.width
              const imgHeight = res.height
              const query = wx.createSelectorQuery().in(that)//in(this),不加有时获取不到对应的DOM元素
              query.select('#myCanvas').fields({ node: true, size: true })
              query.exec((res) => {
                const canvas = res[0].node
                const canvasWidth = res[0].width
                const canvasHeight = res[0].height
      
                const ctx = canvas.getContext('2d')
                // 画布大小初始化
                const dpr = wx.getSystemInfoSync().pixelRatio
                canvas.width = canvasWidth * dpr
                canvas.height = canvasHeight * dpr
                ctx.scale(dpr, dpr)

                const img = canvas.createImage()
                img.src = localImgUrl
                img.onload = () => {

                // 清空画布内容
                  ctx.clearRect(0, 0, canvasWidth, canvasHeight)
                  ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight)
                  // 设置水印样式
                  let fontSize = 20; //水印字体大小
                  let maskText = '我的水印'; //水印文字
                  let fontColor = "#559FFE"; //水印颜色
                  let lineHeight = 80; //水印文字行高
                  let textWidth = 100; //水印文字宽度
                  let diagonalLength = canvasHeight > canvasWidth ? canvasHeight * 2 : canvasWidth; //选取最长边
                  // console.log(diagonalLength);
                // 保证水印文字范围是矩形最长边的2倍
                  ctx.save();
                  ctx.beginPath();
                  ctx.translate(canvasWidth / 2, -diagonalLength);
                  ctx.rotate(45 * Math.PI / 180); //设置文字的旋转角度,角度为45°;
                // 横向循环次数
                  let crossTime = Math.ceil(diagonalLength * 2 / textWidth);
                // 竖向循环次数
                  let verticalTime = Math.ceil(diagonalLength * 2 / lineHeight);
                  for (let j = 0; j < verticalTime; j++) { //纵向循环
                      ctx.font = `${fontSize}px serif`;
                      ctx.fillStyle = fontColor
                      ctx.fillText(maskText, 0, lineHeight * j);
                      for (let i = 1; i < crossTime; i++) { //横向循环
                          ctx.font = `${fontSize}px serif`;
                          ctx.fillStyle = fontColor
                          ctx.fillText(maskText, textWidth * i, lineHeight * j);
                      }
                  };
                  ctx.closePath()
                  ctx.restore()
        
                  // 导出图片并将图片路径返回
                  wx.canvasToTempFilePath({
                    canvas,
                    success: function(res) {
                        // console.log(res.tempFilePath);
                        resolve(res.tempFilePath);
                    },
                    fail: function(err) {
                        reject(err);
                    },
                  })
                }
              })
            },
            fail(err){
                console.log(err)
            }
          })
    })
  },

有一点要提醒小伙伴,如果你和我一样是图片列表的话一定记得要在给图片绘制水印之前清除画布内容,不然你会看到之前绘制的图片出现在下一张里:

ctx.clearRect(0, 0, canvasWidth, canvasHeight)

还是看一下效果吧

完结~~撒花~~~

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值