使用分层画布来优化HTML5渲染的教程

2020-04-24 19:34:57易采站长站整理

 

XML/HTML Code复制内容到剪贴板

var PanningEntity = function() {   
    /**   
     Initialization and other methods   
     **/   
    
    /**   
     * Render call to draw the panned entity   
     *   
     * @param {CanvasRenderingContext2D} context   
     */   
    this.render = function(context) {   
        context.clearRect(   
            this.x,   
            this.y,   
            context.canvas.width,   
            this.height);   
        context.drawImage(   
            this.image,   
            this.x – this.width,   
            this.y – this.height);   
        context.drawImage(   
            this.image,   
            this.x,   
            this.y);   
        context.drawImage(   
            this.image,   
            this.x + this.width,   
            this.y + this.height);   
    }   
};  

因为PanningEntity横跨了整个视区,所以您可以使用画布宽度作为清除矩形的大小。如果使用此清除策略,则会为您提供已为云、小山和地面实体定义的重绘区域。

为了进一步优化云实体,可以将云分离为单独的实体,使用它们自己的重绘区域。这样做会大幅减少在云重绘区域内要清除的屏幕空间量。图 7显示了新的重绘区域。