html52.com
我爱小程序-开发者交流社区

如何解决Canvas 2D使用canvasToTempFilePath?

 onLoad() {
    wx.createSelectorQuery()
      .select('#cardCanvas')
      .fields({
        node: true,
        size: true,
      })
      .exec(this.initCanvas.bind(this))
  },
  initCanvas(res) {
    const width = res[0].width;
    const height = res[0].height;
    const canvas = res[0].node;
    const ctx = canvas.getContext('2d');
    const dpr = wx.getSystemInfoSync().pixelRatio;

    canvas.width = width * dpr;
    canvas.height = height * dpr;
    ctx.scale(dpr, dpr);

    ctx.draw(false() => {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width,
          height,
          destWidth: width,
          destHeight: height,
          canvasId: 'cardCanvas',
          fileType: 'jpg',
          quality: 1,
          success(res) {
            console.log(res.tempFilePath)
          }
        })
      }
    )
  }


场景是在使用canvas2d时导出画布输出到图片,但是发现如下问题

1、使用canvas2d的上下文ctx调用draw()方法的时候报错:ctx.draw is not a function;at SelectorQuery callback function

2、canvasToTempFilePath的官方文档写着在 draw()回调里调用该方法才能保证图片导出成功。文档地址:https://developers.weixin.qq.com/miniprogram/dev/api/canvas/wx.canvasToTempFilePath.html

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

真正的个人免签约支付接口

云免签H5支付