I’ve tried to create a ’tile stamper’ application that allows you to select a tile from the top and then ‘stamp’ that tile onto the canvas area below. You can basically think of this as a map editor for an HTML5 game.
Everything is working except for the selecting and stamping: http://www.exeneva.com/html5/tileStamper
The JS error console says my event listeners aren’t correct, but I am 100% sure they are valid:
// Event listeners
theCanvas.addEventListener("mousemove", onMouseMove, false);
theCanvas.addEventListener("click", onMouseClick, false);
Here is my mouse movement and mouse click handling code:
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);
}
}
Here is the tile highlighting code:
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);
}
Can someone help me figure out why this isn’t working?
According to this line:
theCanvasis jquery wrapper, not a pure DOM Element.So it does not haveaddEventListenermethod.You could try like this: