The giant pit of the WeChat applet wx.canvasToTempFilePath method

Let's first look at the official documentation of wx.canvasToTempFilePath:

wx.canvasToTempFilePath(OBJECT, this)

Export the contents of the specified area of ​​the current canvas to generate a picture of the specified size, and return the file path.

OBJECT parameter description:

parameter Types of Required illustrate Minimum version
x Number no Canvas x-axis start point (default 0) 1.2.0
and Number no Canvas y-axis start point (default 0) 1.2.0
width Number no canvas width (defaults to canvas width-x) 1.2.0
height Number no canvas height (default canvas height-y) 1.2.0
destWidth Number no output image width (default is width) 1.2.0
destHeight Number no output image height (default is height) 1.2.0
canvasId String Yes Canvas ID, pass in the canvas-id of <canvas/>
fileType String no Type of target file, only 'jpg' or 'png' is supported. Default is 'png' 1.7.0
quality Number no The quality of the image, the value range is (0, 1], if it is not within the range, it will be treated as 1.0 1.7.0
success Function no Callback function for successful interface call
fail Function no Callback function for interface call failure
complete Function no The callback function of the end of the interface call (the call will be executed if it succeeds or fails)

Bug & Tip

tip: Only call this method in the draw callback to ensure that the image is exported successfully.

sample code

wx.canvasToTempFilePath({
  x: 100,
  y: 200,
  width: 50,
  height: 50,
  destWidth: 100,
  destHeight: 100,
  canvasId: 'myCanvas',
  success: function(res) {
    console.log(res.tempFilePath)
  } 
})

It looks ok, it works. But a giant pit is coming

wxmlOurs is written like this

<view class="canvas-box" hidden="{{maskHidden}}">
        <canvas  style="width: 262px;height: 467px;" canvas-id="mycanvas"/>
    </view>
    <view class="save" hidden="{{maskHidden}}">点击保存图片</view>

Drawing graphics using Canvas

createNewImg:function(QD){
        var that = this;
        var context = wx.createCanvasContext('myCanvas');
        var path = "https://xcx.upload.utan.com/article/coverimage/2018/01/25/eyJwaWMiOiIxNTE2ODU0MTg2OTY1NSIsImRvbWFpbiI6InV0YW50b3V0aWFvIn0=";

//console.log(QD)
        //var QD = 'https://xcx.upload.utan.com/article/coverimage/2018/01/25/eyJwaWMiOiIxNTE2ODU2Nzc0Njk3OCIsImRvbWFpbiI6InV0YW50b3V0aWFvIn0=';
        //将模板图片绘制到canvas,在开发工具中drawImage()函数有问题,不显示图片
        //不知道是什么原因,手机环境能正常显示
        context.drawImage(path, 0, 0,262,467);

        context.drawImage(QD, 10, 390,65,65);
        //context.draw(true);
        //context.draw();
        context.setFillStyle('#832d3b');
        context.setFontSize(10);
        context.fillText(this.data.remainTxt1, 60, 130, 100);
        context.fillText(this.data.remainTxt3, 80, 155, 100);
        context.fillText(this.data.remainTxt5, 160, 155, 100);
        context.fillText(this.data.remainTxt6, 75, 180, 100);
        context.fillText(this.data.remainTxt8, 140, 180, 100);

        context.setFillStyle('#e24342');
        context.setFontSize(10);
        context.fillText(this.data.remainTxt2, 65, 155, 100);
        context.fillText(this.data.remainTxt4, 150, 155, 100);
        context.fillText(this.data.remainTxt7, 115, 180, 100);

        //绘制图片
        context.draw();
        //将生成好的图片保存到本地,需要延迟一会,绘制期间耗时
        wx.showToast({
            title: '分享图片生成中...',
            icon: 'loading',
            duration:1000
        });
        setTimeout(function(){
            wx.canvasToTempFilePath({
                canvasId: 'mycanvas',
                success: function (res) {
                    var tempFilePath = res.tempFilePath;
                    console.log(tempFilePath);
                    that.setData({
                        imagePath: tempFilePath,
                        maskHidden: false
                        // canvasHidden:true
                    });
                    wx.hideToast()
                },
                fail: function (res) {
                    console.log(res);
                }
            });
        },500);

    },

This is written by this open source project:

Of course, this project can be used, but the image cannot be generated. When opening tempFilePathit, an error is reported. Have you found any reason?

There are two problems here:

  • First: wxmlthere is a problem with asking the price;
  • Second: there is acreateNewImg problem with the method ;context.draw();

To solve the first problem:

What should I do if I encounter this problem? I can't see any problem. Later, when I thought about whether it was placed in the hiddenattribute view, the method viewwas called before the rendering was completed.context.draw()

At this time, I wxmlmodified it

<view class="canvas-box" hidden="{{maskHidden}}">
       
</view>
 <canvas  style="width: 262px;height: 467px;" canvas-id="mycanvas"/>
<view class="save" hidden="{{maskHidden}}">点击保存图片</view>

After running a wave, the picture is actually generated, but the picture drawn is still not just a default background image (maybe there is no background image, just a transparent page)

Later I canvasadded on the above class='test', the same problem reappeared

<canvas  style="width: 262px;height: 467px;" canvas-id="mycanvas" class='test'/>

I don't know why yet.

Anyway, if you're canvasadding properties on , you have to be careful.

To solve the second problem:

In fact, the documentation states:

tip: Only call this method in the draw callback to ensure that the image is exported successfully.

This is misled by open source. .

createNewImg:function(QD){
        var that = this;
        var context = wx.createCanvasContext('myCanvas');
        var path = "https://xcx.upload.utan.com/article/coverimage/2018/01/25/eyJwaWMiOiIxNTE2ODU0MTg2OTY1NSIsImRvbWFpbiI6InV0YW50b3V0aWFvIn0=";

//console.log(QD)
        //var QD = 'https://xcx.upload.utan.com/article/coverimage/2018/01/25/eyJwaWMiOiIxNTE2ODU2Nzc0Njk3OCIsImRvbWFpbiI6InV0YW50b3V0aWFvIn0=';
        //将模板图片绘制到canvas,在开发工具中drawImage()函数有问题,不显示图片
        //不知道是什么原因,手机环境能正常显示
        context.drawImage(path, 0, 0,262,467);

        context.drawImage(QD, 10, 390,65,65);
        //context.draw(true);
        //context.draw();
        context.setFillStyle('#832d3b');
        context.setFontSize(10);
        context.fillText(this.data.remainTxt1, 60, 130, 100);
        context.fillText(this.data.remainTxt3, 80, 155, 100);
        context.fillText(this.data.remainTxt5, 160, 155, 100);
        context.fillText(this.data.remainTxt6, 75, 180, 100);
        context.fillText(this.data.remainTxt8, 140, 180, 100);

        context.setFillStyle('#e24342');
        context.setFontSize(10);
        context.fillText(this.data.remainTxt2, 65, 155, 100);
        context.fillText(this.data.remainTxt4, 150, 155, 100);
        context.fillText(this.data.remainTxt7, 115, 180, 100);

        //将生成好的图片保存到本地,需要延迟一会,绘制期间耗时
        wx.showToast({
          title: '分享图片生成中...',
          icon: 'loading',
          duration: 1000
        });

        //绘制图片
        context.draw(false, wx.canvasToTempFilePath({
          canvasId: 'mycanvas',
          success: function (res) {
            var tempFilePath = res.tempFilePath;
            console.log(tempFilePath);
            that.setData({
              imagePath: tempFilePath,
              maskHidden: false
              // canvasHidden:true
            });
            wx.hideToast()
          },
          fail: function (res) {
            console.log(res);
          }
        }));
    },

In fact, WeChat applet is not a new thing, it has been out for more than a year, but it is still relatively new to our team, and we are only preparing for the project this week. . . So record this problem here, I hope that the partners who use this method will pay attention. .

If you have any questions, you can leave a message on my official account:

Quanke Longting

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324606138&siteId=291194637