8

微信小程序Canvas绘制证件照底色,小程序Canvas绘图

 2 years ago
source link: https://segmentfault.com/a/1190000040700247
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

微信小程序Canvas绘制证件照底色,小程序Canvas绘图

小程序提供了Canvas绘图的API,我们很轻松就可以使用Canvas绘制一张图片并保存下来。本次案例使用绘制证件照的方式演示Canvas的示例。

去掉背景的证件照(宽160px,高230px)

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
            })
          }
        })
      }
    })
  }
})

开发过程中可以使用本地图片进行开发,实际应用需要使用网络图片,那么就需要使用wx.downloadFile接口下载下来,保存为本地临时文件,然后使用临时文件的地址进行绘图!

TANKING
https://github.com/likeyun


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK