刚学习微信小游戏,使用原生引擎与基础库,做了一个简单画布添上背景图;然后再添加了一个离屏画布,画了一个矩形,接着2秒延迟将矩形清除一部分。看了几遍api文档,问了几个AI工具,都没有解决问题。 请大神帮忙分析一下问题,非常感谢。
预期效果:
但实际效果没有做到清除,日志正常。
完整代码如下(清除逻辑bindEvent函数):
const WINDOW_INFO = wx.getWindowInfo();
const IMAGE_SRC="images/index_bg2.jpg";
const BACKGROUND_WIDTH = 1312;
const BACKGROUND_HEIGHT = 736;
/**
// * 游戏主函数
*/
export default class Main {
constructor() {
//解决重新进入游戏出现黑屏问题
console.log('高性能模式',GameGlobal.isIOSHighPerformanceMode);
this.init();
}
/**
* 初始化
*/
init(){
//创建画布
this.canvas = wx.createCanvas();
this.canvas.width = WINDOW_INFO.screenWidth;
this.canvas.height = WINDOW_INFO.screenHeight;
//获取canvas的2D绘图上下文,画笔
this.context = this.canvas.getContext("2d");
//设置背景图片
this.image = wx.createImage();
this.image.src= IMAGE_SRC;
this.imageLoaded = false;
this.image.onload=()=>{
this.imageLoaded = true;
};
//将图片绘制到画布上, 并且渲染至屏幕
requestAnimationFrame(this.render.bind(this));
}
/**
* 绘制
*/
render(){
const timeId= setInterval(() => {
if(this.imageLoaded){
console.log('图片加载成功了');
clearInterval(timeId);
this.context.drawImage(
this.image,
0,
0,
BACKGROUND_WIDTH,
BACKGROUND_HEIGHT,
0,
0,
this.canvas.width,
this.canvas.height
);
this.bindEvent();
}else{
console.log('图片加载中');
}
}, 100);
}
/**
* 测试离屏清除
*/
bindEvent(){
//创建离屏画布
const secondScreenCanvas = wx.createCanvas();
secondScreenCanvas.width = 100;
secondScreenCanvas.height = 100;
this.secondScreenCtx = secondScreenCanvas.getContext('2d');
//在离屏左上角绘制红色100*100矩形
this.secondScreenCtx.fillStyle ='red';
this.secondScreenCtx.fillRect(0, 0, 100, 100);
//同步至主屏
this.context.drawImage(secondScreenCanvas, 0, 0);
//二秒后清除一小块50*50红色区域
setTimeout(()=>{
this.secondScreenCtx.clearRect(0, 0, 50, 50);
//重新绘制到主画布,确保清除效果可见
requestAnimationFrame(()=>{
this.context.drawImage(secondScreenCanvas, 0, 0);
console.log('清除完成');
});
},2000);
}
}