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);
  }

 

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值