Search code examples
javascripthtmlcanvashtml5-canvasmouse-coordinates

How can canvas coordinates be converted into tile coordinates?


So I have a canvas with an isometric tile map drawn on it, which looks perfect.

In the event listener at the bottom of the script, I grab the cursor's coordinates inside the canvas. How could I find out which tile the cursor is hovering over?

var cs = document.getElementById('board');

var c = cs.getContext("2d")
var gridWidth=100
var gridHeight=50
var tilesX = 12, tilesY = 12;
var spriteWidth=gridWidth
var spriteHeight=img.height/img.width*gridWidth
cs.width = window.innerWidth //spriteWidth*10
cs.height = window.innerHeight //spriteHeight*10
var ox = cs.width/2-spriteWidth/2
var oy = (tilesY * gridHeight) / 2

window.onresize=function(){
cs.width = window.innerWidth //spriteWidth*10
cs.height = window.innerHeight //spriteHeight*10
ox = cs.width/2-spriteWidth/2
oy = (tilesY * gridHeight) / 2
draw()
}

draw();


function renderImage(x, y) {
c.drawImage(img, ox + (x - y) * spriteWidth/2, oy + (y + x) * gridHeight/2-(spriteHeight-gridHeight),spriteWidth,spriteHeight)
}

function draw(){
for(var x = 0; x < tilesX; x++) {
    for(var y = 0; y < tilesY; y++) {
        renderImage(x,y)
    }
}
}

cs.addEventListener('mousemove', function(evt) {
var x = evt.clientX,
y = evt.clientY;
console.log('Mouse position: ' + x + ',' + y);
}, false);

Sorry for pasting such lengthy code, but all of it is there just to lay the isometric grid.

EDIT: Also, how could I get the top left coordinates of the tile image to relay it?


Solution

  • Assuming you've arranged your tiles where the leftmost column and topmost row are zero:

    var column = parseInt(mouseX / tileWidth);
    
    var row = parseInt(mouseY / tileHeight);
    

    BTW, if you eventually move your canvas off the top-left of the page then you must adjust your mouse coordinates by the canvas offset.

    Here's an example of how to calculate mouse position:

    // references to the canvas element and its context
    
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    
    // get the offset position of the canvas on the web page
    
    var BB=canvas.getBoundingClientRect();
    var offsetX=BB.left;
    var offsetY=BB.top;
    
    // listen for mousedown events
    
    canvas.onmousedown=handleMousedown;
    
    function handleMousedown(e){
    
         // tell the browser we will handle this event
    
         e.preventDefault();
         e.stopPropagation();
    
         // calculate the mouse position
    
         var mouseX=e.clientX-offsetX;
         var mouseY=e.clientY-offsetY;
    
    }