uniapp canvas 上传图片添加水印

发布时间 2023-11-22 10:34:40作者: 躺尸的大笨鸟
  1. 隐藏canvas,position:fixed;left:100%
 <canvas
    :style="{width:canvasWidth,height:canvasHeight}"
    style="position:fixed;left:100%;"
    canvas-id="myCanvas"
  ></canvas>
  1. 上传图片添加水印
//别忘了第二个参数this
uni.getImageInfo({
        src: filePath,
        success: (res) => {
          // 设置画布高度和宽度
          this.canvasWidth = `${res.width}px`
          this.canvasHeight = `${res.height}px`
          const ctx = uni.createCanvasContext('myCanvas', this)
          ctx.clearRect(0, 0, res.width, res.height)
          ctx.beginPath()
          ctx.drawImage(filePath, 0, 0, res.width, res.height)

          ctx.translate(res.width / 2, res.height / 2)
          ctx.rotate((-30 * Math.PI) / 180)
          const horizontal = res.width / 6
          const vertical = res.height / 3
          const fonsize = res.width / 30
          // 列
          for (let i = 0; i <= 8; i++) {
            // 行
            for (let j = 0; j <= 6; j++) {
              ctx.beginPath()
              ctx.setFontSize(`${fonsize}px serif`)
              ctx.setFillStyle('rgba(0, 0, 0, 0.5)')
              ctx.setStrokeStyle('rgba(0, 0, 0, 0.5)')
              // 调整距离
              ctx.fillText('仅用于****小程序实名认证使用', (i * horizontal - res.width / 4) * 4, j * vertical - res.height, fonsize * 30)
            }
          }
          // 开始绘制添加水印的图片并显示在页面中
          ctx.draw(false, () => {
            setTimeout(() => {
              uni.canvasToTempFilePath({
                canvasId: 'myCanvas',
                // 设置输出的图片的宽度高度,会加快输出图片时间
                destWidth: res.width,
                destHeight: res.height,
                fileType: 'jpg', // jpg为了压缩
                quality: 0.8, // 图片的质量
                success: (res) => {
                  //调用接口 上传图片
                  this.uploadImg(res.tempFilePath, prop)
                },
                fail: (err) => {
                  console.log(err)
                  this.formData[`${prop}Loading`] = false
                },
              }, this)
            }, 500)
          })
        },
        fail: (err) => {
          console.log(err)
        },
      })