我试图创建一个“瓷砖压模”应用程序,它允许您从顶部选择一个瓷砖,然后将该瓷砖“印章”到下面的画布区域。您基本上可以将其视为 HTML5 游戏的地图编辑器。
除了选择和标记外,一切正常:http ://www.exeneva.com/html5/tileStamper
JS 错误控制台说我的事件监听器不正确,但我 100% 确定它们是有效的:
// Event listeners
theCanvas.addEventListener("mousemove", onMouseMove, false);
theCanvas.addEventListener("click", onMouseClick, false);
这是我的鼠标移动和鼠标点击处理代码:
function onMouseMove(e) {
// Accounts for the canvas not being at the top left of screen
mouseX = e.clientX - theCanvas.offsetLeft;
mouseY = e.clientY - theCanvas.offsetTop;
}
function onMouseClick(e) {
console.log("click: " + mouseX + "," + mouseY);
if (mouseY < 128) {
// Find tile to highlight
var totalRows = 7; // 8 total rows, but relative zero means we use 7
var col = Math.floor(mouseX / tileLength);
var row = Math.floor(mouseY / tileLength);
var tileId = (row * totalRows) + (col + row);
highlightTile(tileId, col * tileLength, row * tileLength);
} else {
// stamp the selected tile
var col = Math.floor(mouseX / tileLength);
var row = Math.floor(mouseY / tileLength);
context.putImageData(imageData, col * tileLength, row * tileLength);
}
}
这是瓷砖突出显示的代码:
function highlightTile(tileId, x, y) {
// redraw tilesheet and highlight selected tile
context.fillStyle = "#aaaaaa";
context.fillRect(0, 0, 256, 128);
drawTileSheet();
imageData = context.getImageData(x, y, 32, 32);
// set alpha to 128
for (j = 3; j < imageData.data.length; j += 4) {
imageData.data[j] = 128;
}
// draw red line around selected tile
var startX = Math.floor(tileId % 8) * 32;
var startY = Math.floor(tileId / 8) * 32;
context.strokeStyle = "red";
context.strokeRect(startX, startY, 32, 32);
}
有人可以帮我弄清楚为什么这不起作用吗?