ミニ プログラムのキャンバスを通じて画像を生成して保存する

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. レンダリング

ここに画像の説明を挿入します

おすすめ

転載: blog.csdn.net/qq_37332614/article/details/132402398