Image rotation by three affine transformations

Via that same Hacker News piece that generated “Image rotation by shifting pixels” (2021-11-13): Any angular rotation can be expressed as the sum of three shear transformations. Shear right, then down, then right again; the result is an angular rotation!

In writing this JavaScript code I learned about the context.setTransform function, which makes the code for shearing an image almost disappointingly easy, and this “rotation by composing affine transformations” business almost obvious.

Unlike the previous method for rotating by 90 degrees, this sum-of-shears method requires some pixels to move by non-integer amounts. You can deal with this either by interpolating their color values (which introduces blurring, even when rotating by 90 degrees) or by snapping to the pixel grid (which makes this approach “pixel-conserving” in the same way as the previous recursive-rotation approach).

Check it out on your own sample image below:

The Javascript/Canvas code embedded in the iframe above is also downloadable here.

Posted 2021-11-26