关于canvas:微信小程序Canvas绘制证件照底色小程序Canvas绘图

8次阅读

共计 1154 个字符,预计需要花费 3 分钟才能阅读完成。

小程序提供了 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
            })
          }
        })
      }
    })
  }
})

演示

作者

TANKING
https://github.com/likeyun

正文完
 0