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

1. html

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

javascript 复制代码
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

css 复制代码
.canvas {
  margin: auto;
  font-size: 0;
}

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

4. 效果图

相关推荐
小小王app小程序开发9 小时前
淘宝扭蛋机小程序核心玩法拆解与技术运营分析
大数据·小程序
说私域11 小时前
AI智能名片商城小程序数据清洗的持续运营策略与实践研究
大数据·人工智能·小程序·流量运营·私域运营
东东51612 小时前
xxx食堂移动预约点餐系统 (springboot+微信小程序)
spring boot·微信小程序·小程序·毕业设计·个人开发·毕设
CHU72903513 小时前
一番赏盲盒抽卡机小程序:解锁惊喜体验与社交乐趣的多元功能设计
前端·小程序·php
2501_9159184115 小时前
HTTPS 代理失效,启用双向认证(mTLS)的 iOS 应用网络怎么抓包调试
android·网络·ios·小程序·https·uni-app·iphone
数字游民952715 小时前
半年时间大概上了70个web站和小程序,累计提示词超过20w
人工智能·ai·小程序·vibecoding·数字游民9527
说私域16 小时前
微商企业未来迭代的核心方向与多元探索——以链动2+1模式AI智能名片商城小程序为核心支撑
大数据·人工智能·小程序·流量运营·私域运营
276695829216 小时前
美团 小程序 mtgsig
python·小程序·node·js·mtgsig1.2·美团小程序·大众点评小程序
2501_9151063217 小时前
混合应用(Hybrid)安全加固,不依赖源码对成品 IPA 混淆
android·安全·小程序·https·uni-app·iphone·webview
00后程序员张18 小时前
无需越狱,来对 iOS 设备进行调试、管理与分析
android·ios·小程序·https·uni-app·iphone·webview