Flip images horizontally, vertically, or both directions instantly
The HTML5 Canvas API doesn't actually have a native flip() or mirror() function. To reverse an image, developers have to use a mathematical trick leveraging the scale() transformation.
Normally, calling scale(1, 1) means draw the image at 100% width and 100% height. If we want to flip the image horizontally, we apply scale(-1, 1).
This tells the canvas to draw the image at negative 100% width, which mathematically causes the pixels to render in reverse order, effectively flipping it.
However, drawing at a negative width has a side effect: it means the entire image gets drawn backwards off the left side of the screen into negative coordinate space (outside the visible bounds of the canvas).
To fix this, before we scale, we first have to mathematically translate() the origin point (0,0) of the canvas from the top-left corner over to the far right edge, and then draw it backwards so it lands exactly inside the canvas bounds.
How do you tell an HTML5 Canvas to draw an image upside-down (flipped vertically)?