4
头图

The applet provides Canvas drawing API, we can easily use Canvas to draw a picture and save it. This case demonstrates the Canvas example by drawing ID photos.

Prepare

ID photo with background removed (width 160px, height 230px)

Code

index.wxml

<!-- Canvas 2D组件 -->
<canvas canvas-id="firstCanvas" class="firstCanvas"></canvas>
<!-- 保存按钮 -->
<button bindtap="saveimg" class="saveimg">保存到相册</button>

index.wxss

.firstCanvas{
      width: 160px;
      height: 230px;
      margin:30px auto 0;
}
.saveimg{
      margin-top: 30px;
}

index.js

Page({
  canvasIdErrorCallback: function (e) {
    console.error(e.detail.errMsg)
  },
  onReady: function (e) {
    // 使用 wx.createContext 获取绘图上下文 context
    var context = wx.createCanvasContext('firstCanvas')
    // 设置边框颜色
    context.setStrokeStyle("#fff")
    // 设置边框粗细
    context.setLineWidth(0)
    // 设置背景颜色
    context.setFillStyle("#f00")
    context.fillRect(0, 0, 160, 230)
    // 将人像绘制上去
    context.drawImage('../images/1.png',0,0,160,230)
    // 创建一个矩形
    context.rect(0, 0, 160, 230)
    context.stroke()
    context.draw()
  },
  // 保存图片到相册
  saveimg(){
    var that = this;
    // 先将Cnavas绘制成临时文件
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 160,
      height: 230,
      destWidth: 160,
      destHeight: 230,
      canvasId: 'firstCanvas',
      success(res) {
        console.log(res.tempFilePath)
        // 再保存到相册
        wx.saveImageToPhotosAlbum({
          filePath:res.tempFilePath,
          success(res) { 
            wx.showToast({
              title: '已保存',
              icon: 'success',
              duration: 2000
            })
          }
        })
      }
    })
  }
})

Demo

Mini program experience

Idea expansion

You can use local pictures for development during the development process. Actual applications need to use network pictures, so you need to download them using the wx.downloadFile interface, save them as local temporary files, and then use the address of the temporary file for drawing!

author

TANKING
https://github.com/likeyun


TANKING
4.8k 声望493 粉丝

热爱分享,热爱创作,热爱研究。