Component中canvas的draw回调函数无法进入
发布于 5 年前 作者 yinqiang 13436 次浏览 来自 问答
  • 当前 Bug 的表现(可附上截图)

    Component中canvas的draw回调函数无法进入, 只打印了1

  • 预期表现

    回调函数会进入,并打印1 和 2

  • 复现路径

见Demo

  • 提供一个最简复现 Demo

    const context = wx.createCanvasContext(‘xx_canvas’);

    context.setFillStyle(‘red’)

    context.fillRect(10, 10, 150, 100)

    console.log(“1”);

    context.draw(false, function(e) {

        console.log(“2”);

        // do something…

        wx.canvasToTempFilePath({

            x: 0,

            y: 0,

            width: 650,

            height: 960,

            canvasId: ‘xx_canvas’,

            fileType: ‘png’,

            success: function (res) {

                let pic = res.tempFilePath;

                console.log(pic);

                wx.previewImage({

                    urls: [res.tempFilePath],

                })

            }

        });

    })

只打印了“1”,未打印2.

4 回复

Draw回调加延时换成setTimeout就好了,代码如下

const context = wx.createCanvasContext('xx_canvas');
 
   context.setFillStyle('red')
 
   context.fillRect(10, 10, 150, 100)
 
   console.log("1");
 
   context.draw(false, setTimeout(function(e) {
 
       console.log("2");
 
       // do something...
 
       wx.canvasToTempFilePath({
 
           x: 0,
 
           y: 0,
 
           width: 650,
 
           height: 960,
 
           canvasId: 'xx_canvas',
 
           fileType: 'png',
 
           success: function (res) {
 
               let pic = res.tempFilePath;
 
               console.log(pic);
 
               wx.previewImage({
 
                   urls: [res.tempFilePath],
 
               })
 
           }
 
       });
 
   },300))

draw的callback函数外面包一层等待canvas渲染的时间,不同设备有部分差异,200毫秒基本都能满足

const context = wx.createCanvasContext(‘xx_canvas’, this)

wx.canvasToTempFilePath 也要加上第二个参数 this

回到顶部