小程序中通过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. 效果图

相关推荐
游戏开发爱好者814 分钟前
TCP 抓包分析:tcp抓包工具、 iOS/HTTPS 流量解析全流程
网络协议·tcp/ip·ios·小程序·https·uni-app·iphone
2501_916008892 小时前
iOS 26 软件性能测试全流程,启动渲染资源压力对比与优化策略
android·macos·ios·小程序·uni-app·cocoa·iphone
00后程序员张2 小时前
iOS 26 兼容测试实战,机型兼容、SwiftUI 兼容性改动
android·ios·小程序·uni-app·swiftui·cocoa·iphone
OEC小胖胖3 小时前
连接世界:网络请求 `wx.request`
前端·微信小程序·小程序·微信开放平台
mon_star°3 小时前
基于微信小程序高仿背单词消除游戏
游戏·微信小程序·小程序
jingling5553 小时前
解决微信小程序真机调试中访问本地接口 localhost:8080 报错
前端·微信小程序·小程序
ZeroNews内网穿透3 小时前
新版发布!“零讯”微信小程序版本更新
运维·服务器·网络·python·安全·微信小程序·小程序
molong9313 小时前
Android 应用配置跳转微信小程序
android·微信小程序·小程序
尘似鹤3 小时前
微信小程序学习(二)
学习·微信小程序·小程序
杏花春雨江南3 小时前
微信小程序里 uni.navigateTo 用的多了, 容易报错,
微信小程序·小程序·notepad++