缩放 js canvas 模式的问题

Issues scaling a js canvas pattern

我需要一个用棋盘格图案填充的大矩形,并且它必须能够缩放。当我一个一个地绘制每个方块时,最终结果就是我想要的,但是一旦我有数千个方块来创建每一帧,这就是一种非常低效的绘制方式。为了解决这个问题,我决定创建一个图案 canvas 并用一个简单的图案填充整个区域。

以下是两种方法的示例: https://jsfiddle.net/Stephen_Witwick/zpunh195/150/

左边的黑色棋盘图案是用图案 canvas 创建的,红色棋盘是通过绘制每个单独的方块创建的。

这是有效但速度较慢的代码:

//unitWidth and unitHeight are the dimensions of each square. Since the checkerboard uses squares, they are the same value
//boxWidthUnits and boxHeightUnits are the dimensions of the checkerboard by number of squares

for(let i = 0; i < boxWidthUnits/2; i++){
    for(let j = 0; j < boxHeightUnits/2; j++){
        ctx.fillRect(2*i*unitWidth,2*j*unitHeight,unitWidth,unitHeight);
        ctx.fillRect(2*(i+1/2)*unitWidth,2*(j+1/2)*unitHeight,unitWidth,unitHeight)
    }
}

有没有办法让我从红色棋盘中得到结果而不那么慢?

问题是因为大多数时候 unitWidth/height 是一个像素的一小部分,但图案大小必须是一个整数(因为它是图像)。

例如,当 n=15 时,单元大小为 10.375,但 patternCanvas 大小四舍五入为 20x20。在这种情况下,每个图案都缺少 0.75px * 10 个适合正方形的图案,总共 7.5px。

肉眼无法察觉,但如果您保存 canvas 图像并使用图像编辑器,您可以看到图案几乎总是缺少 right/bottom[=10= 的一部分]