Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Canvas Transformation Matrix

I don't understand what the Transformation Matrix is and how to work with it.

The following will draw a circle at 0, 0 of my canvas: (generated from an svg converted with svg2canvas.jar)

drawPoints: function(ctx, max_points)
        {
            ctx.save();

            ctx.setTransform(1, 0, 0, 1, -551.23701, -368.42499);

            ctx.fillStyle="#0066ab";
            ctx.globalAlpha="0.7";
            ctx.beginPath();
            ctx.moveTo(584.50,387.96);
            ctx.bezierCurveTo(584.50,397.14,577.05,404.59,567.87,404.59);
            ctx.bezierCurveTo(558.68,404.59,551.24,397.14,551.24,387.96);
            ctx.bezierCurveTo(551.24,378.77,558.68,371.33,567.87,371.33);
            ctx.bezierCurveTo(577.05,371.33,584.50,378.77,584.50,387.96);
            ctx.closePath();
            ctx.fill();

            ctx.restore();
        }

I would like to pass in arguments for setTransform() to draw on any part of my canvas, however I don't understand how to use it at all.

like image 347
Russell Avatar asked Sep 02 '10 19:09

Russell


1 Answers

The transformation matrix gets multiplied by each point before it's drawn on the canvas. Like @Eric said, it's an affine transformation matrix from linear algebra. In your example, it would work like this:

[ x']   [ 1 0 -551.23701 ] [ x ]   [ x - 551.23701 ]
[ y'] = [ 0 1 -368.42499 ] [ y ] = [ y - 368.42499 ]
[ 1 ]   [ 0 0    1       ] [ 1 ]   [       1       ]

So it shifts the x and y coordinates by -551.23... and -368.42... respectively.

Other types of transformations involve different "slots" in the matrix. For example, here's the matrix that scales the drawing by sx and sy (x and y scaling factors):

[ sx  0 0 ]
[  0 sy 0 ]
[  0  0 1 ]

and rotation (angle is in radians):

[ cos(angle) -sin(angle) 0 ]
[ sin(angle)  cos(angle) 0 ]
[     0           0      1 ]

The advantage of using a transformation matrix over calling individual methods, like translate, scale, and rotate, is that you can perform all the transformations in one step. It gets complicated though when you start combining them in non-trivial ways because you need to multiply the matrices together to get the final result (this is what functions like scale, etc. are doing for you). It's almost always easier to call each function instead of calculating it yourself.

The links @Eric mentioned and the transformation matrix article on Wikipedia go into a lot more detail about how it all works.

like image 169
Matthew Crumley Avatar answered Oct 16 '22 23:10

Matthew Crumley