收藏
回答

请教如何清除离屏画布上的局部内容

框架类型 问题类型 终端类型 微信版本 基础库版本
小游戏 需求 微信iOS客户端 8.0.58 3.8

刚学习微信小游戏,使用原生引擎与基础库,做了一个简单画布添上背景图;然后再添加了一个离屏画布,画了一个矩形,接着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(00100100);
            //同步至主屏
            this.context.drawImage(secondScreenCanvas, 00);
            
            //二秒后清除一小块50*50红色区域
            setTimeout(()=>{
                this.secondScreenCtx.clearRect(005050);
                //重新绘制到主画布,确保清除效果可见
                requestAnimationFrame(()=>{
                    this.context.drawImage(secondScreenCanvas, 00);
                    console.log('清除完成');
                }); 
            },2000);
    }     
}


回答关注问题邀请回答
收藏
登录 后发表内容