# Isometric Cubes in Canvas

## Recommended Posts

jeremythuff    108

Hello,

I am trying draw cubes in canvas. I want to call the function cube(x,y) and have a cube draw at that spot. In the function cube I am looping over an array of matrices that are being passed into .setTransform(). the issue is that once I dial in the x and y offset at an x and y of 0,0 that offset need does not work for x,y 100,100.

I need a formula for the x and y offset that will allow it to be accurate no mater what x and y value has been passed into my function. I guess i need some sort of constant or something to tame the shift of x and y.

I have a fiddle here that illustrates my issue: http://jsfiddle.net/jeremythuff/S9TGU/324/

and here is my function:

function cube(x,y){
var faces = [
[1,-0.5,1,0.5,x,y],
[1,-0.5,0,1,x+w,y+(h/2)],
[1,0.5,0,-1,x,y+h]
];

\$(faces).each(function() {
var matrix = this;
ctx.save();
ctx.setTransform(
matrix[0],
matrix[1],
matrix[2],
matrix[3],
matrix[4],
matrix[5]
);
ctx.strokeRect(x, y, w, h);
ctx.restore();
});
} 

any guidance will be appreciated.

##### Share on other sites
jeremythuff    108

If there is some way that I can clarify my question please let me know :)

##### Share on other sites
LJ_1102    1233
ctx.setTransform(
matrix[0],
matrix[1],
matrix[2],
matrix[3],
matrix[4],
matrix[5]
);
//ctx.strokeRect(x, y, w, h);
ctx.strokeRect(0,0,w,h);


You're applying the transforms two times thats why the "planes" are shifted.

The last two indices of your matrix (4,5) are already a translation in space, using strokeRect with with x, y arguments

causes the translation to be applied again.

I've adjusted your fiddle accordingly, take a look at MDN Transforms article for further information.

EDIT:

I added some colors to make it look more isometric.

http://jsfiddle.net/jeremythuff/S9TGU/324/

Merry X-Mas

Edited by LJ_1102

##### Share on other sites
jeremythuff    108

thanks, :) it's all clear now!