小程序使用 canvas 给图片添加水印

小程序使用 canvas 给图片添加水印

操作 canvas 相关的 api 使用的是微信最新提供的 (一路过来踩了好多坑…)

浅用微信小程序 canvas 给图片添加简单水印, 废话不多说, 先上效果, 后看代码 (uniapp等框架写法大同小异)

效果图

6901c35965fc25fbcf08fa61269e7dd.jpg

464e6e80ca6dd6bce029b696920f2f1.jpg

代码部分 (没有细分拆开来讲, 但大部分代码都加解释注释了)

WXML

<view class="container">
  <button bindtap="chooseImages">选择图片</button>
  <view>
    <image src="{
   
   {imgsrc}}" mode="aspectFit" bindtap="prevImage"></image>
  </view>
</view>
<canvas style="position:fixed;top: 0;left: -100%" type="2d" id="Canvas"></canvas>

JavaScript

Page({
  data: {
    imgsrc: '',
    canvas: null,
    ctx: null,
  },
  // 在页面初次渲染完成生命周期获取操作canvas的上下文对象
  onReady() {
    const query = wx.createSelectorQuery()
    query.select('#Canvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        this.setData({ canvas, ctx })
      })
  },
  // 选择图片
  async chooseImages() {
    const res = await wx.chooseImage({})
    const addWatermarkRes = await this.addWatermark(res.tempFilePaths[0])
  },
  // 添加水印方法 (传入图片地址)
  addWatermark(tempFilePath) {
    return new Promise( async (resolve, reject) => {
        // 获取图片信息
        const imgInfo = await wx.getImageInfo({ src: tempFilePath })
        // 设置canvas宽高
        this.data.canvas.width = imgInfo.width
        this.data.canvas.height = imgInfo.height
        // 创建一个图片对象
        const image = this.data.canvas.createImage();
        image.src = tempFilePath;
        image.onload = () => {
          // 将图片绘制到canvas上
          this.data.ctx.drawImage(image, 0, 0, imgInfo.width, imgInfo.height)
          // 设置文字字号及字体
          this.data.ctx.font = '32px sans-serif'
          // 设置画笔颜色
          this.data.ctx.fillStyle = 'rgba(0,0,0,0.3)';
          // 绘制矩形
          this.data.ctx.fillRect(0, imgInfo.height - 40, 420, 40)
          // 设置画笔颜色
          this.data.ctx.fillStyle = '#ffffff';
          // 填入文字
          this.data.ctx.fillText('品名: 巨无霸汉堡; 单价: 20元', 0, imgInfo.height - 10)
          // 将canvas转为为图片
          wx.canvasToTempFilePath({
            canvas: this.data.canvas,
            success: (res) => {
              this.setData({ imgsrc: res.tempFilePath})
              resolve(res.tempFilePath)
            },
          })
        }
    })
  },
  // 预览图片
  prevImage(){
    wx.previewImage({
      current: this.data.imgsrc, // 当前显示图片的http链接
      urls: [this.data.imgsrc] // 需要预览的图片http链接列表
    })
  }
})

有问题可以评论区或者私信讨论哈

猜你喜欢

转载自blog.csdn.net/weixin_47170010/article/details/123463994