1

我正在使用 javascript、CSS 和 HTML 绘制一个屏幕,方法是使用 for 循环以 16X16 的间隔遍历屏幕宽度和高度。这是我的循环当前的样子:

{
        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的混合将所有这些图块绘制到屏幕上?

4

1 回答 1

3

您通过这种方式创建过多的回流/布局事件。由于您删除了所有项目然后再次添加它们(这两种方式都非常昂贵),因此只需添加所有 div 一次,并且由于它们始终处于相同的顺序,只需更新现有的。

另外,要快速清除 div,请执行div.innerHTML = '';. 如果附加大量项目,请将它们添加到虚拟 div,然后将虚拟 div 附加到实际附加到 DOM 的 div(例如,您可以使用 document.getElement??? 函数查询的div)。

在初始化中:

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]];
        }
    }
}
于 2011-09-11T07:21:48.723 回答