Cartezian coordinate system in HTML 5 canvas

Normally canvas 2D context is using custom coordinate transform where Y coordinates are flipped vertically. Here is image with example (taken from http://diveintohtml5.info/canvas.html; it is great book and you should read it 🙂 )

It is a bit inconvenient to use if you are drawing some shapes with points given in classic Cartezian coordinate system.

Luckily we can change it with setTransform function of canvas context object. How? It is pretty easy:

__context.setTransform(1, 0, 0, -1, 0, currentHeight);

where __context is canvas context and currentHeight is actual height of a canvas element.

I used this in my little library for drawing 2d graphs, which I described in mine previous post Simple 2D graphs. You can see example of this little snippet in action right there.

I hope this will help someone. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
16 + 27 =