微信小程序canvas 2d 绘制图片与文字 导出图片

wxml内容 如下

<canvas id="myCanvas" type="2d"
	style="width: {{ canvas.width }}px;height: {{ canvas.height }}px;">
</canvas>
<button bindtap="generatePicture">生成图片</button>

JS内容

在 onReady 生命周期拿到canvas实例

data:{
  canvas:{ width:150, height:300 },
},
onReady() {
  this.createSelectorQuery().select('#myCanvas')
  .fields({ node: true, size: true })
  .exec((res) => {
    this.setData({
      canvas: res[0].node
    })
  })
},

在 点击生成图片 按钮

// 拿到图片信息,获取宽高,使其完整地将显示在页面上 
// 类似于 <image mode="aspectFit"/> 
// 可以跳过此步骤
generatePicture(){
  return this.apiPromise('getImageInfo', { src: 图片路径 })
  .then(e=>{
    const canvas = this.data.canvas
    const { screenWidth, screenHeight } = wx.getSystemInfoSync()
    const { width, height } = e
    const multipleH = height/screenHeight
    const multipleW = width/screenWidth
    if(width/multipleH>screenWidth){
      canvas.width = width/multipleW
      canvas.height = height/multipleW
    }else {
      canvas.width = width/multipleH
      canvas.height = height/multipleH
    }
    this.setData({
      canvas,
    })
    return this.drawImage(this.data.canvas)
  })	
},

往canvas里绘制图片,绘制完成执行 drawText()

drawImage({width, height}){
  return new Promise(resolve=>{
    const ctx = this.data.canvas.getContext('2d')
    const img = this.data.canvas.createImage()
    img.src = this.data.originUrl
    img.onload = () => {
      ctx.drawImage(img, 0, 0, width, height)
      resolve(this.drawText(ctx, width, height))
    }
  })
},

往canvas里绘制图片,绘制完成执行 drawText()

drawText(ctx, width, height){
  const values = [{
	color:'red', // 文字颜色
	size:18, // 文字大小
	x:0, // 文字坐标
	y:0, // 文字坐标
	text:'测试文字', // 文字	
  }]
  values.forEach(item=>{
    ctx.fillStyle = item.color
    ctx.font = `${item.size}px sans-serif`
    ctx.fillText(item.text, item.x, item.y)
  })
  return this.exportCanvasImage(width, height)
},

使用 canvasToTempFilePath Api 导出图片 res.tempFilePath为图片路径

 exportCanvasImage(width, height){
   return this.apiPromise('canvasToTempFilePath',{
      canvas: this.data.canvas,
      width,
      height,
   })
   .then(res=>{
     return res.tempFilePath
   })
},

一个小轮子, 将wx api转为promise

/**
 * 将wx api转为promise 执行
 *  示例 : apiPromise('getUserProfile',{ desc:'获取用户信息' })
 * @param { String } api wx api 名字
 * @param { Object } arg 参数
 * @returns { Promise }
 */
apiPromise(api, arg = {}){
  return new Promise((resolve, reject) => {
    const success = arg.success
    const fail = arg.success
    arg.success = (e) => {
      resolve(e)
      success?.apply(this, e)
    }
    arg.fail = (e) => {
      reject(e)
      fail?.apply(this, e)
    }
    wx[api](arg)
  })
}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值