繁体   English   中英

用HTML5绘制最快的方法是什么

[英]What is the fastest way to draw in HTML5

我通过使用for循环以16X16的间隔遍历屏幕的宽度和高度,使用javascript,CSS和HTML在Web上绘制屏幕。 这是我的循环当前的样子:

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

通过这种方式,您正在创建大量的重排/布局事件。 由于您删除了所有项目,然后又添加了它们(这样做的方式都非常昂贵),因此只需将所有div添加一次,并且由于它们始终处于相同的顺序,只需更新现有的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]];
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM