2011-09-11 103 views
1

我正在使用javascript,CSS和HTML通過使用for循環遍歷屏幕寬度和高度以16X16的間隔來繪製屏幕。下面是我的循環目前的樣子:在HTML5中繪製最快的方式是什麼?

{ 
     div = document.getElementById('mainView'); 
     while (div.children.length > 0) 
      div.removeChild(div.children[0]); 

     for (y = this.y; y < this.y + this.height; ++y) 
     { 
      for (x = this.x; x < this.x + this.width; ++x) 
      { 
       toAppend = document.createElement('div'); 
       viewCoords = this.convertWorldToView(x, y); 
       toAppend.style.top = viewCoords[1] * 16 + 'px'; 
       toAppend.style.left = viewCoords[0] * 16 + 'px'; 
       mainViewDiv.appendChild(toAppend); 
       if (fullMap[y][x] == TILE_WATER) 
       { 
        startTile = Math.round(Math.random() * 3) + 1; 
        toAppend.className = "Water" + startTile + "Tile"; 
       } 
       else 
       { 
        toAppend.className = typeClassDecoder[fullMap[y][x]]; 
       } 
      } 
     } 
    } 

有提請所有這些瓷磚使用或者帆布或某些功能的JavaScript或JavaScript和CSS混合畫面更快的方法?

+0

如果我得到它正確地要刪除其所有內容後添加的div在平鋪方式。 –

+0

沒有完整的代碼,沒有標記/ css,很難理解發生了什麼。我建議你把你的代碼放在jsfiddle(http://jsfiddle.net/)中並提供鏈接。 –

+0

在jsfiddle上的類似任務的例子在這裏:http://jsfiddle.net/robhawkes/cV3Rr/ –

回答

3

您正在通過這種方式創建過量的迴流/佈局事件。既然你刪除了所有的項目,然後重新添加它們(這兩個方法都是昂貴的),相反,只需添加一次div,並且由於它們總是以相同的順序,只需更新現有的項目即可。

此外,要快速清除div,請執行div.innerHTML = '';。如果追加大量項目,將它們添加到一個虛擬div,然後將虛擬div附加到實際連接到DOM的div(例如,可以使用document.getElement ???函數查詢的div)。

在INIT:

div = document.getElementById('mainView'); 
for (y = this.y; y < this.y + this.height; ++y) 
{ 
    for (x = this.x; x < this.x + this.width; ++x) 
    { 
     toAppend = document.createElement('div'); 
     viewCoords = this.convertWorldToView(x, y); 
     toAppend.style.top = viewCoords[1] * 16 + 'px'; 
     toAppend.style.left = viewCoords[0] * 16 + 'px'; 
     mainViewDiv.appendChild(toAppend); 
    } 
} 

在渲染:

div = document.getElementById('mainView'); 
var i = 0; 

for (y = this.y; y < this.y + this.height; ++y) 
{ 
    for (x = this.x; x < this.x + this.width; ++x) 
    { 
     toAppend = div.children[i++]; 
     if (fullMap[y][x] == TILE_WATER) 
     { 
      startTile = Math.round(Math.random() * 3) + 1; 
      toAppend.className = "Water" + startTile + "Tile"; 
     } 
     else 
     { 
      toAppend.className = typeClassDecoder[fullMap[y][x]]; 
     } 
    } 
} 
+0

謝謝你,速度驚人的事情。你認爲使用畫布會更快嗎?或者有沒有其他方法可以更快地繪製這樣的瓷磚? – vternal3

+0

畫布可以更快,但我不會立即下注。畢竟,在JavaScript代碼+ canvas不一定匹配的現代瀏覽器中,類切換使用本地渲染優化。我會做一些快速的基準。作爲一般規則,優化應始終遵循測試。在上述情況下,我已經測試過這些情況(例如,元素創建,附件等),但我沒有自己測試畫布瓷磚盒。 – Sajid

相關問題