[html5] canvas shape rotatation & order of execution

Domenic Denicola d at domenic.me
Sun Jan 31 21:44:50 PST 2016

From: Help [mailto:help-bounces at lists.whatwg.org] On Behalf Of Dean, John

> My code below successfully rotates a drawing object at the center of the drawing object, but I want to understand happens behind the scenes:
> 1. ctx.translate(100, 100);
> 2. ctx.rotate(Math.PI / 4);
> 3. ctx.translate(-100, -100);
> 4. ctx.fillRect(50, 80, 100, 40);
> https://html.spec.whatwg.org/multipage/scripting.html#current-transformation-matrix says transformations are performed in reverse order. Does that mean the execution order is 4, 3, 2, 1? Or 3, 2, 1, 4? More importantly, how does it work exactly?

Only your first three operations are transformations (a translation, a rotation, and a translation). These help build up the transformation matrix, which is then applied to drawing operations like fillRect. The following background reading may help: https://en.wikipedia.org/wiki/Transformation_matrix

The "reverse order" comment is essentially a comment about how matrix multiplication works. As Wikipedia says, "Note that the multiplication is done in the opposite order from the English sentence: the matrix of "A followed by B" is BA, not AB." This is because you transform the vector according to B*A*x = B*(A*x), i.e. you apply A first, then apply B to the result.

More information about the Help mailing list