复制 JavaScript 画布中的磁贴区域

Copy a tile area in javascript canvas

本文关键字:区域 布中 JavaScript 复制      更新时间:2023-09-26

我有一个显示磁贴地图的画布。滚动时,我希望选择可以重复使用的磁贴地图的有用部分并将其复制到另一个画布,而不是刷新整个磁贴列表。

例如,如果磁贴地图有 5 个磁贴:

0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8

我想向右移动 (x) 1 个瓷砖...我可以将磁贴 1 复制到 4,因为它们将在下一帧中使用。所以我会复制:

1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
5 6 7 8

我似乎在为此想出正确的数学时遇到了问题。

目前我有以下代码:

// Calculate from and to for x and y
// Change formula if positive or negative movement
    // movX / movY = amount to move across x or y
    // (i.e. movX = 1 (right) or movX = -1 (left)
    // tileXFrom / tileYFrom = tile to start copy from
    // tileXTo / tileYTo = tile to finish copying at
if(movX > 0)
{
    tileXFrom = origX + movX;
    tileXTo = tileXFrom + (tilesCountX - movX);
}
else
{
    tileXFrom = origX;
    tileXTo = tileXFrom + (tilesCountX + movX);
}
if(movY > 0)
{
    tileYFrom = origY + movY;
    tileYTo = tileYFrom + (tilesCountY - movY);
}
else
{
    tileYFrom = origY;
    tileYTo = tileYFrom + (tilesCountY + movY);
}

这些计算工作正常,但是有更好的方法来做它们吗?我想知道是否有办法绕过正/负 if 语句。

我现在陷入困境的部分是如何为每个位置获得真正的 x、y 位置。

所以我需要将瓷砖 1, 0 转换为屏幕上的 x, y 位置,以便从那里开始复制。

如果这一切都有意义?!

干杯

您可以使用三元运算符来缩短代码,但这不会更改功能:

tileXFrom = (movX > 0) ? origX + movX : origX;
tileXTo   = (movX > 0) ? tileXFrom + (tilesCountX - movX) : tileXFrom + (tilesCountX + movX);
tileYFrom = (movY > 0) ? origY + movY : origY;
tileYTo   = (movY > 0) ? tileYFrom + (tilesCountY - movY) : tileYFrom + (tilesCountY + movY);