微信小程序 新版canvas绘制图片方法

截至2025.06.16,因微信小程序开发文档介绍不全,很多用户绘制图片不显示或失败。本文给出截至目前的可行方案,还提醒新手若不熟悉canvas,可先查看小程序官方文档,同时给出了可运行案例。

截至2025.06.16 修改日可用

微信小程序开发文档介绍不全,导致很多用户绘制图片不显示或失败,因此写下截至目前的可行方案

<canvas type="2d" id="myCanvas"></canvas>

// canvas 标签中要使用id, 不要只用canvas-id,没有id,wx.createSelectorQuery().select('#myCanvas') 获取不到节点
wx.createSelectorQuery().select('#myCanvas')
  .fields({ node: true, size: true })
  .exec((res) => {
      let textCanvas = res[0].node;  // 重点1

      textCtx = textCanvas.getContext('2d');  // 重点2
 
      /**至此,textCanvas,textCtx已经成功获取到,下面代码为绘图测试代码可根据自己需要修改**/

      textCtx.clearRect(0,0,textCanvas.width,textCanvas.height)
      textCtx.beginPath();

      const bg = textCanvas.createImage();
      bg.src = 'https的网络图';
      bg.onload = () => {
            textCtx.drawImage(bg, 0, 0, textCanvas.width, textCanvas.height)
      }
})

如果新手不熟悉canvas,先看下小程序官方文档

可运行案例:

wxml:

<canvas type="2d" id="myCanvas" style="width: 750rpx;height: 200rpx;"></canvas>

js:

let textCtx;
Page({
  data: {

  },
  onLoad() {
    wx.createSelectorQuery().select('#myCanvas').fields({ node: true, size: true })
      .exec((res) => {
          let textCanvas = res[0].node  // 重点1

          textCtx = textCanvas.getContext('2d')  // 重点2
 
           /**至此,textCanvas,textCtx已经成功获取到,下面代码为绘图测试代码可根据自己需要修改**/

          textCtx.clearRect(0,0,textCanvas.width,textCanvas.height)
          textCtx.beginPath();

          const bg = textCanvas.createImage()
          bg.src = '替换自己的网络图链接'
          bg.onload = () => {
            textCtx.drawImage(bg, 0, 0, textCanvas.width, textCanvas.height)
          }
        })
  }

})

评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值