Master Canvas Image Rotation and Flipping with Transformations and Pixel Manipulation
This tutorial explains how to rotate, flip, and mirror images on an HTML5 canvas using coordinate system transforms, matrix operations, and pixel‑level manipulation, providing step‑by‑step code examples and visual diagrams for each technique.
Demand Background
In a game scene many bubble‑like elements share the same irregular shape but need different animation states, rotation angles and horizontal mirroring. Canvas is chosen for its performance and the bubbles are rendered as pre‑drawn images.
Canvas Coordinate System
The 2D canvas coordinate system matches the browser’s coordinate system: the origin (0,0) is at the top‑left corner, the X axis grows to the right and the Y axis grows downward.
<canvas id='myCanvas'></canvas>
var canvas = document.getElementById('myCanvas');
canvas.width = 750;
canvas.height = 1054;
var ctx = canvas.getContext('2d');Drawing an Image
Use drawImage() after the image has fully loaded.
var img = new Image();
img.src = 'bubble.png';
img.onload = function() {
ctx.drawImage(img, 512, 220, 160, 192);
};Canvas Transformations
The 2D context provides four basic transformation functions:
translate(x, y) – moves the origin by x pixels horizontally and y pixels vertically.
rotate(angle) – rotates the coordinate system clockwise by angle radians.
scale(sx, sy) – scales the axes; values greater than 1 enlarge, values between 0 and 1 shrink.
transform(a, b, c, d, e, f) / setTransform(a, b, c, d, e, f) – apply a 2×3 matrix directly. The parameters have the following meaning: a: horizontal scaling b: horizontal skewing c: vertical skewing d: vertical scaling e: horizontal translation f: vertical translation
Image Rotation
To rotate a bubble (width 160 px, height 192 px) located at (512, 220) by 35° counter‑clockwise:
ctx.save();
ctx.translate(512 + 160/2, 220 + 192/2); // move origin to image centre
ctx.rotate(-35 * Math.PI / 180); // negative for counter‑clockwise
ctx.drawImage(img, -160/2, -192/2, 160, 192);
ctx.restore();Image Horizontal Flipping
To flip a bubble at (172, 365) horizontally and then rotate it 35° clockwise:
ctx.save();
ctx.translate(172 + 160/2, 365 + 192/2);
ctx.scale(-1, 1); // mirror on the X axis
ctx.rotate(35 * Math.PI / 180);
ctx.drawImage(img, -160/2, -192/2, 160, 192);
ctx.restore();Matrix‑Based Transformations
The same visual effect can be produced with a single transform() call. The rotation matrix is:
x' = x * cosθ - y * sinθ
y' = x * sinθ + y * cosθScaling, shearing and mirroring have analogous matrix forms and can be combined by multiplying the matrices before passing the final six values to transform() or setTransform().
Pixel‑Level Horizontal Flipping
Canvas pixel manipulation can also achieve a flip by swapping pixel data.
// Draw the original image
ctx.drawImage(img, x, y, w, h);
// Retrieve pixel data
var imgData = ctx.getImageData(x, y, w, h);
var h = imgData.height, w = imgData.width, half = w >> 1;
for (var row = 0; row < h; row++) {
for (var col = 0; col < half; col++) {
var i = (row * w + col) * 4; // index of left pixel
var i2 = (row * w + (w - col - 1)) * 4; // index of right pixel
// swap RGBA channels
for (var p = 0; p < 4; p++) {
var tmp = imgData.data[i + p];
imgData.data[i + p] = imgData.data[i2 + p];
imgData.data[i2 + p] = tmp;
}
}
}
ctx.putImageData(imgData, x, y);Summary of Techniques
Basic Transformations – use save(), translate(), rotate(), scale(), draw the image, then restore(). This approach is concise and hardware‑accelerated.
Matrix Transformations – compute a combined transformation matrix and apply it with transform() or setTransform(). Useful when multiple transforms need to be merged into a single operation.
Pixel Manipulation – retrieve image data with getImageData(), manually swap pixels, and write back with putImageData(). Provides fine‑grained control but is slower because it bypasses GPU acceleration.
References
W3cplus – Canvas series
HTML5 Canvas transform documentation
HTML5 Canvas study notes
Flipping images in HTML5
All examples assume a 2D canvas context.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Aotu Lab
Aotu Lab, founded in October 2015, is a front-end engineering team serving multi-platform products. The articles in this public account are intended to share and discuss technology, reflecting only the personal views of Aotu Lab members and not the official stance of JD.com Technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
