2013-08-18 68 views
0

我試圖繪製一個n×n的正方形網格,其中每個正方形由彼此頂部繪製的顏色層組成。使用fillRect()將顏色繪製到畫布上似乎工作正常,不會出現任何資源。但是,當我嘗試使用rect()在每個方塊周圍添加邊框時,性能明顯下降。Canvas Optimization with rect()and fillRect()

在每次調用下面的函數之前,我使用clearRect()清除畫布。

有問題的功能:

/** 
* Draws an n x n grid of layered color squares of the given width. 
* @param {int} `width`  The width of each square in the grid. 
* @param {int} `leftOffSet` The left margin of the grid. 
* @param {int} `topOffSet` The top margin of the grid. 
* @param {int} `n`   The dimension of the grid. 
* @param {object} `layers' A linked-list of color layers. 
*/ 
function drawMap(width, leftOffSet, topOffSet, n, layers) { 
    for (var i = 0; i < n; i++) { 
     for (var j = 0; j < n; j++) { 

      var currentLayer = layers[i][j]; 
      while (typeof currentLayer.tile !== 'undefined') { 
       var bg = currentLayer.tile.background; 

       context.fillStyle = 'rgba(' + bg.r + ',' + bg.g + ',' + bg.b + ',' + bg.a + ')'; 
       context.fillRect(i * width + leftOffSet, j * width + topOffSet, width, width); 

       currentLayer = currentLayer.next; 
      } 

      // BOTTLE NECK APPEARS TO BE HERE 
      /*context.beginPath(); 
      context.rect(i * width + leftOffSet, j * width + topOffSet, width, width); 
      context.stroke(); 
      context.closePath();*/ 

     } 
    } 
} 

隨着註釋掉瓶頸,性能優良,但只要我取消註釋塊時,性能下降。有沒有優化這個方法?

回答

1

把context.stroke循環

沒有必要中風,你把它定義每個單獨矩形之外 - 在剛剛結束context.stroke一次。

function drawMap(width, leftOffSet, topOffSet, n, layers) { 

    // begin a new path 
    context.beginPath(); 

    for (var i = 0; i < n; i++) { 
     for (var j = 0; j < n; j++) { 

      var currentLayer = layers[i][j]; 
      while (typeof currentLayer.tile !== 'undefined') { 
       var bg = currentLayer.tile.background; 

       context.fillStyle = 'rgba(' + bg.r + ',' + bg.g + ',' + bg.b + ',' + bg.a + ')'; 
       context.fillRect(i * width + leftOffSet, j * width + topOffSet, width, width); 

       currentLayer = currentLayer.next; 
      } 

      // define new rects, 
      // but don't stroke every new rect 
      context.rect(i * width + leftOffSet, j * width + topOffSet, width, width); 

      // closePath is not needed if you're just rect-ing 
      // context.closePath(); 


     } 
    } 

    // all done defining rects, now just do 1 stroke that draws them all 
    context.stroke(); 

} 
+0

這樣做的伎倆,謝謝。 – Deomachus