Image Flipping with JavaScript Canvas
Flip and mirror images client-side using the HTML Canvas API — with step-by-step code examples.
Published:
Tags: image flip JavaScript Canvas, flip image Canvas API, JavaScript mirror image
Image Flipping with JavaScript Canvas The HTML Canvas API flips images by transforming the drawing coordinate system — mirrors horizontally, mirrors vertically — before calling . --- What is how canvas transformations work? The Canvas 2D context maintains a transformation matrix that maps your drawing coordinates to screen pixels. Before drawing anything, you can modify this matrix: — multiplies x and y coordinates by the given factors — shifts the origin point — rotates around the current origin When you call , every x coordinate is negated. A pixel at x=100 now draws at x=−100. Combined with , the drawing space is shifted right so the negated coordinates fall within the visible canvas area. This approach is non-destructive: the original image data is untouched. The transformation only…
Frequently Asked Questions
How do I flip an image with Canvas?
Create a canvas, get its 2D context, apply scale(-1, 1) for a horizontal flip, translate(-canvas.width, 0) to move the drawing origin, then drawImage(img, 0, 0). The combination of scale and translate places the flipped image correctly within the canvas bounds.
How do I mirror an image in JavaScript?
Horizontal mirroring (left-right flip) uses context.scale(-1, 1) followed by context.translate(-canvas.width, 0) before drawing. Vertical mirroring (top-bottom flip) uses context.scale(1, -1) followed by context.translate(0, -canvas.height).
How do I rotate an image 90 degrees with Canvas?
For a 90° clockwise rotation, create a canvas with swapped dimensions (height becomes width and vice versa), translate to (canvas.width, 0), then rotate(Math.PI / 2) before drawing. Ensure you set canvas width and height to the rotated dimensions before transforming.
What is the transform scale(-1, 1) trick?
scale(-1, 1) flips the coordinate system horizontally — the x-axis runs right-to-left instead of left-to-right. Any subsequent drawing operation is mirrored. The translate(-width, 0) call compensates so the image draws at the correct position rather than off the left edge of the canvas.
How do I export a flipped Canvas as a file?
Use canvas.toBlob(callback, 'image/jpeg', 0.9) for a JPEG with 90% quality or canvas.toBlob(callback, 'image/png') for lossless PNG. Inside the callback, create an object URL with URL.createObjectURL(blob) and trigger a download link programmatically.
All articles · theproductguy.in