Categories
JavaScript Web development

Fun with canvas transforms

Making use of coordinate system transformations can make drawing on the html5 element canvas much easier. But sometimes it is confusing how transforms work. What is it that is actually transformed?

Active or passive?

A simple example. Let’s draw a square in the left top corner of a canvas

JS

Now we could apply a transform, like

JS

And you might expect that the square we have drawn will move 75 pixels to the right and 50 pixels down. But that doesn’t happen. One might say the transformation is passive: it leaves already drawn graphics alone.

Coordinate systems

What translate (or any canvas transform) does is change the coordinate system of the rendering context. If we would now draw a second square, with the same parameters for left and top, this square would appear 75 pixels to the right and 50 pixels down.

JS

So the canvas itself has a fixed coordinate system, with the origin in the top-left corner. We can manipulate (transform) the rendering context’s coordinate sytems, but as soon as something is drawn it is fixed to the canvas. To move an existing graphic, or scale or rotate it, you just have to redraw it from scratch, using a suitable transformation.

Cherries

Well, let’s make use of those transforms and create the following graphic with minimal math trouble.

You see that the drawing consists of multiple copies of a basis element, a cherry with a stem (or a circle with a line if you like). It would be quite a lot of work if we had to calculate all coordinates of every copy. Instead we just transform the rendering context and draw one copy each time, calling drawCherry() in the code below.

JS