小程序中通过canvas生成并保存图片

1. html

<canvas class="canvas" id="photo" type="2d" style="width:200px;height: 300px;">canvas>
<button bindtap="saveImage">保存button>

<image src="{{tempFilePath}}" mode="widthFix" />

2. js

data: {
  canvas: null,  //canvas 对象
  tempFilePath: ""
},

onLoad(options) {
  wx.createSelectorQuery()
    .select('#photo') // 在 canvas的 id
    .fields({
      node: true,
      size: true
    })
    .exec((res) => {
      // Canvas 对象
      const canvas = res[0].node
      this.setData({ //这里保存canvas对象是因为下面保存相片要用这个对象
        canvas
      })
      // 渲染上下文
      const ctx = canvas.getContext('2d')
      // canvas 画布的实际绘制宽高
      const width = res[0].width
      const height = res[0].height
      // 初始化画布大小
      const dpr = wx.getWindowInfo().pixelRatio
      canvas.width = width * dpr
      canvas.height = height * dpr
      ctx.scale(dpr, dpr)
      // 清空画布
      ctx.clearRect(0, 0, width, height)
      //canvas背景色
      ctx.fillStyle = '#3c9cff';
      ctx.fillRect(0, 0, 200, 300);
      // 图片对象
      const image = canvas.createImage()
      image.src = '/images/640.png'
      image.onload = () => {
        // 将图片绘制到 canvas 上
        ctx.drawImage(image, 0, 0, 200, 300)
      }
   })
},
// 生成图片
saveImage() {
  wx.canvasToTempFilePath({
    canvasId: 'photo',
    destWidth: 286,
    destHeight: 417,
    canvas: this.data.canvas,
    success: (res) => {
      this.setData({
        tempFilePath: res.tempFilePath
      })
      wx.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success: (res)=> {
          wx.showToast({
            title: '保存成功',
          })
        }
      })
    }
  });
},

3. css

.canvas {
  margin: auto;
  font-size: 0;
}

.show {
  width: 200px;
  margin: auto;
  display: block;
}

4. 效果图

小程序中通过canvas生成并保存图片_第1张图片

你可能感兴趣的:(微信小程序,小程序)