关于canvas:微信小程序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
            })
          }
        })
      }
    })
  }
})

演示

作者

TANKING
https://github.com/likeyun

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理