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

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

图 7. 具有单独重绘区域的云
201558170334513.jpg (300×169)

单一实体清除策略产生的解决方案可以解决像本例这样的分层画布游戏上的大多数问题,但仍然可以对它进行优化。为了寻找针对该渲染策略的极端情况,我们假设球会与三角形碰撞。如果两个实体碰撞,实体的重绘区域就有可能发生重叠,并创建一个不想要的渲染构件。另一个清除优化,更适合于可能会碰撞的实体,它也将有益于分层。
脏矩形清除

若没有单一清除策略,脏矩形清除策略可以是一个功能强大的替代品。您可以对有重绘区域的大量实体使用这种清除策略,这种实体包括密集的粒子系统,或有小行星的空间游戏。

从概念上讲,该算法会收集由算法管理的所有实体的重绘区域,并在一个清除调用中清除整个区域。为了增加优化,此清除策略还会删除每个独立实体产生的重复清除调用,如清单 7所示。
清单 7.DirtyRectManager
 

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

var DirtyRectManager = function() {   
    // Set the left and top edge to the max possible   
    // (the canvas width) amd right and bottom to least-most   
    
    // Left and top will shrink as more entities are added   
    this.left   = canvas.width;   
    this.top    = canvas.height;   
    
    // Right and bottom will grow as more entities are added   
    this.right  = 0;   
    this.bottom = 0;   
    
    // Dirty check to avoid clearing if no entities were added   
    this.isDirty = false;   
    
    // Other Initialization Code   
    
    /**   
     * Other utility methods   
     */   
    
    /**   
     * Adds the dirty rect parameters and marks the area as dirty