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

本文介绍了如何在微信小程序中使用HTML5的CanvasAPI,结合Wx.createSelectorQuery和canvasToTempFilePath方法,实现用户生成并保存图片的功能,展示了从绘图到保存的完整过程。

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. 效果图

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值