0

我正在尝试绘制一个 n×n 的正方形网格,其中每个正方形由相互叠加的颜色层组成。使用 fillRect() 将颜色绘制到画布上似乎可以正常工作并且不会占用任何资源。但是,当我尝试使用 rect() 在每个正方形周围添加边框时,性能明显下降。

在每次调用以下函数之前,我使用 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();*/

        }
    }
}

注释掉瓶颈后,性能很好,但是一旦我取消注释该块,性能就会下降。有没有办法优化这个?

4

1 回答 1

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();

}
于 2013-08-18T21:36:06.823 回答