关于前端:小程序使用-canvas-给图片添加水印

7次阅读

共计 1733 个字符,预计需要花费 5 分钟才能阅读完成。

小程序应用 canvas 给图片增加水印

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

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

效果图

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

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 链接列表
    })
  }
})

有问题能够评论区或者私信探讨哈

正文完
 0