微信小程序
问题描述
当使用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);
}