wx:if 跟 canvas繪圖 一起使用的bug 微信小程序 canvas 繪圖的踩坑

微信小程序

問題描述

當使用wx:if="{{showStatus}}"  去切換canvas 的消失與出現時,第一次渲染會成功
關閉即設置showStatus爲false,然後再次設置showStatus爲true,會發現canvas 標籤出現,但是內容爲空

解決方案

1、this.setData({
showStatus爲true
}) 時,不要立刻執行渲染函數,設置一個定時器,即

setTimeout(this.onDrawCanvasHandler,20)

大於20ms 就可以,但是這種做法不太保險,這個定時器的時候不確定

2、使用hidden="{{!showStatus}}"代替 wx:if
3、canvas 使用position,隱藏時,設置top/left/right/bottom 無限遠即可

例子如下
wxml 文件

<!--pages/canvasTest/canvasTest.wxml-->
<view class='pengyouquan' catchtap='showHandler'>aaa</view>

<view wx:if="{{showStatus}}">
  <view catchtap='closeHandler'>guanbi</view>
  <button type="primary" bindtap="save">保存當前繪圖</button>
  <canvas canvas-id="myCanvas" class='canvas'/> 
</view>

js文件
 

showHandler:function(){
    this.setData({
      showStatus:true
    })
    this.onDrawCanvasHandler()
    // setTimeout(this.onDrawCanvasHandler,20)
    
  },
  closeHandler:function(){
    this.setData({
      showStatus: false
    })
  },
  onDrawCanvasHandler:function(){
    let windowWidth = this.windowWidth;
    let WidthRadio = this.WidthRadio;
    console.log("windowWidth", windowWidth)
    console.log("WidthRadio", WidthRadio)
    let ctx = wx.createCanvasContext('myCanvas');
    console.log(ctx)
    // ctx.setFontSize(20)
    // ctx.fillText('Hello', 20, 20)
    // ctx.fillText('MINA', 100, 100)
    ctx.clearRect(0, 0, 0, 0);
    ctx.setFillStyle("#ffe200");
    ctx.fillRect(0, 0, windowWidth, 667);
    
    var path = "../../imgs/icon-logo-circle.png";
    ctx.drawImage(path, (30 * WidthRadio), (30 * WidthRadio), (315 * WidthRadio), 183);
    // var path2 = "../../imgs/erweima.jpg";
    ctx.drawImage(path, (windowWidth - 30 * WidthRadio - 120 * WidthRadio), (230), (120 * WidthRadio), (120 * WidthRadio));

    ctx.setTextAlign('left');

    ctx.setFillStyle("#000000");
    ctx.setFontSize(16);
    ctx.fillText("必燃特賣歡迎你", 20, 20);
    ctx.draw(false);
  }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章