将画布划分为相同宽度和高度的空间
你首先需要确定的是如何你想划分空间:
- 按固定数量的列和行
- 按预定义的平铺宽度和高度。
对于后者,您可能希望将大小调整为最接近的大小,但为了简单起见,请坚持第一种方法。
假设您想要固定数量的图块:
var columns = 6,
rows = 4;
那么每个图块的大小将是:
var tileWidth = canvas.width / columns,
tileHeight = canvas.height / rows;
这个数字可能是也可能不是一个浮点数。如果您只需要整数值,您只需将它们四舍五入:
var tileWidth = Math.round(canvas.width / columns),
tileHeight = Math.round(canvas.height / rows);
现在您可以使用索引来确定每个图块的位置:
var x = xIndex * tileWidth,
y = yIndex * tileHeight;
这个x和y可以直接用来设置一个tile的位置。
如果你想“捕捉”你需要使用相对于画布的鼠标位置的图块:
canvas.onmousemove = function(e) {
/// adjust mouse position to be relative to canvas
var rect = canvas.getBoundingClientRect(),
mx = e.clientX - rect.left,
my = e.clientY - rect.top,
/// get index from mouse position
xIndex = Math.round(mx / tileWidth),
yIndex = Math.round(my / tileHeight);
/// calculate x and y based on previous formula
}
您可能希望从图块的中心而不是角落捕捉。只需从鼠标位置减去一半的平铺宽度和高度即可。
xIndex = Math.round((mx - tileWidth * 0.5) / tileWidth);
yIndex = Math.round((my - tileHeight * 0.5) / tileHeight);
您可能需要检查索引范围(xIndex >= 0 && xIndex