# HTML5 canvas screen to isometric coordinate conversion

I am trying to create an isometric game using HTML5 canvas, but don't know how to convert HTML5 canvas screen coordinates to isometric coordinates. My code now is:

var mouseX = 0;
var mouseY = 0;
function mouseCheck(event) {
mouseX = event.pageX;
mouseY = event.pageY;
}


which gives me canvas coordinates. But how do I convert these coordinates to isometric coordinates? I am using 16x16 tiles.

Check out the code examples at Andres Pagella's github repo. It's the example code that goes along with his book on isometric social games in HTML5. The book explains the math behind the transformation, or you could try and puzzle it out from one his examples, like this one.

It is probably going to depend on how you define your world grid, but the tutorials posted earlier are good. I wrote an html5 game engine and open sourced it here: https://github.com/j03m/trafficcone

Docs are still a little rough, but there are some usable/runnable examples. The Isometric game world model shows some of the code needed to do those translations.

Check out this class, it contains a bunch of helper functions designed to hide some of the complexity - but its a bit coupled to how we do things (tiles + cells):

https://github.com/j03m/trafficcone/blob/master/public/tccore/GameWorldModelIso.js

 getWorldCellFromScreenCoord: function (screenX, screenY) {
var pos = this.getCell(screenX, screenY);
pos.x = pos.x + this.cameraX;
pos.y = pos.y + this.cameraY;
return pos;
},
getCell: function (screenX, screenY) {

var screenLocationX = screenX - this.originX;
var screenLocationY = this.originY - screenY;

var ym = (2 * screenLocationY - screenLocationX) / 2;

var xm = screenLocationX + ym;
var tw = this.cellWidth;
var th = this.cellHeight;

if (xm > 0) {
xm = xm + tw / 2
}
else {
xm = xm - tw / 2;
}

if (ym > 0) {
ym = ym + th / 2
}
else {
ym = ym - th / 2
}

var ty = this.rightFloor(ym / th);
var tx = this.rightFloor(xm / tw);

return { "x": -tx, "y": -ty };
}


But this is again heavily tied to how you decide to do your coordinate system, the direction of your x/y/z axis (0->max or max->0) and if you use cells.

• You should paste question-specific code here instead of just putting a link to your project. – Tetrad Jan 20 '12 at 20:13
• Understood - revised. – j03m Jan 20 '12 at 20:22