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

相关推荐
2501_916007471 天前
提升 iOS 26 系统流畅度的实战指南,多工具组合监控
android·macos·ios·小程序·uni-app·cocoa·iphone
一匹电信狗1 天前
【MySQL】数据库表的操作
linux·运维·服务器·数据库·mysql·ubuntu·小程序
2501_915921431 天前
iOS 应用代上架流程,多工具组合与使用 开心上架 跨平台自动化上传指南
android·ios·小程序·uni-app·自动化·cocoa·iphone
知识分享小能手1 天前
uni-app 入门学习教程,从入门到精通,uni-app组件 —— 知识点详解与实战案例(4)
前端·javascript·学习·微信小程序·小程序·前端框架·uni-app
Q_Q19632884751 天前
python+uniapp基于微信小程序的助眠小程序
spring boot·python·小程序·django·flask·uni-app·node.js
韩立学长1 天前
基于微信小程序的公益捐赠安全平台9hp4t247 包含完整开发套件(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·微信小程序·小程序
2501_915918411 天前
iOS 混淆与 IPA 加固一页式行动手册(多工具组合实战 源码成品运维闭环)
android·运维·ios·小程序·uni-app·iphone·webview
流***陌2 天前
扭蛋机 Roll 福利房小程序前端功能设计:融合趣味互动与福利适配
前端·小程序
亮子AI2 天前
【小程序】微信小程序点击效果(view、button、navigator)
微信小程序·小程序
future_studio2 天前
聊聊 Unity(小白专享、C# 小程序 之 加密存储)
开发语言·小程序·c#