X33*_*X33 3 2d canvas isometric html5-canvas
我的网格
tileWidth = 64px
tileHeight = 128px
Run Code Online (Sandbox Code Playgroud)
(图像本身为128px,但实际的钻石高32px,宽64px)

如你所见,我有一个交错的网格系统; 然而,我花了最后两个小时试图想出一个系统,我可以相对于画布获取鼠标坐标,并找出点击了什么样的瓷砖(显然是在菱形字段内).
例如,如果我点击了瓷砖21, 26- 我将如何在程序中找到它?
我们将非常感谢能够朝着正确方向努力的任何指示.谢谢!
小智 7
如果你知道单元格的中心位置,当然你要渲染它们,你只需要对单元格进行标准化,找出它是否在里面:
var dx = Math.abs(x - cellCenterX),
dy = Math.abs(y - cellCenterY);
if (dx / (cellWidth * 0.5) + dy / (cellHeight * 0.5) <= 1) { /* is inside */ };
Run Code Online (Sandbox Code Playgroud)
这是一个完整的演示:
var cw = 64,
ch = 32,
cells = [],
maxH = 10,
maxV = 5,
toggle = true,
canvas = document.getElementById("canvas"),
ctx = canvas.getContext('2d');
// Using a cell object for convenience here:
function Cell(posX, posY, x, y, w, h) {
this.posX = posX; // some id....
this.posY = posY; // some id....
this.x = x; // cells top position
this.y = y;
this.w = w; // width and height of cell
this.h = h;
this.centerX = x + w * 0.5; // abs. center of cell
this.centerY = y + h * 0.5;
}
// draw this cell:
Cell.prototype.render = function(ctx, color) {
ctx.beginPath();
ctx.moveTo(this.centerX, this.y);
ctx.lineTo(this.x + this.w, this.centerY);
ctx.lineTo(this.centerX, this.y+this.h);
ctx.lineTo(this.x, this.centerY);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
ctx.strokeStyle = "#000";
ctx.stroke();
};
// check if x/y is inside this cell
Cell.prototype.isInCell = function(x, y) {
var dx = Math.abs(x - this.centerX),
dy = Math.abs(y - this.centerY);
return (dx / (this.w * 0.5) + dy / (this.h * 0.5) <= 1);
};
// generate cell map
for(var y = 0; y < maxV; y++) {
var dltX = toggle ? 0 : -cw * 0.5,
dltY = -ch * 0.5 * y;
toggle = !toggle;
for(var x = 0; x < maxH; x++) {
var c = new Cell(x, y, x * cw + dltX, y * ch + dltY, cw, ch);
cells.push(c);
c.render(ctx, "#9f0"); // green bg
}
}
// test by clicking in cell
canvas.onclick = function(e) {
var r = canvas.getBoundingClientRect(),
x = e.clientX - r.left,
y = e.clientY - r.top,
i = 0, cell;
for(; cell = cells[i]; i++) {
if (cell.isInCell(x, y)) {
cell.render(ctx, "#f00"); // red bg if inside
out.innerHTML = "Cell pos: (" + cell.posX + "," + cell.posY + ") X: " + cell.x + " Y: " + cell.y;
break;
}
}
};Run Code Online (Sandbox Code Playgroud)
<canvas id=canvas width=500 height=100></canvas><br>
<output id=out></output>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1469 次 |
| 最近记录: |