How to Flip and Mirror an Image in JavaScript (CSS & Canvas)
Flipping an image in JavaScript takes one line for the display case and four for the file case: img.style.transform = 'scaleX(-1)' mirrors what the browser paints, while a canvas translate + scale(-1, 1) + drawImage writes a mirrored bitmap you can upload. The two are not interchangeable — a CSS flip leaves img.src untouched, so a download or a FormData upload of that image is still unflipped.
That distinction is why the selfie preview looks right and the uploaded avatar looks wrong, and why a scanned back-side page still reads backwards after a CSS-only “fix”. Below are both paths, plus the SDK route for flipping batches of scanned pages.
What you’ll build: A browser tool that flips or mirrors images horizontally and vertically using three methods — CSS transforms, HTML5 Canvas 2D context, and Dynamic Web TWAIN for batch document processing.
Key Takeaways
- Horizontal flip and mirror are the same operation:
scaleX(-1). Vertical flip isscaleY(-1). Omitting thetranslatestep is the usual reason a canvas flip comes out blank or half-empty. - CSS
transformmirrors only what the page paints. CanvasdrawImageplustoBlob()produces new pixels that survive a save, an upload, or an OCR pass. - Flipping both axes is identical to rotating 180°:
scale(-1, -1)androtate(180deg)produce the same image, so pick whichever reads more clearly in the code. - Mirroring a page does not make mirrored text readable. A document that arrived as a mirror image has to be flipped back to its original handedness; a 180° rotation is a different transform.
- Dynamic Web TWAIN exposes native
Mirror(horizontal) andFlip(vertical) methods that batch-process scanned images without a canvas round-trip per page.
Common Developer Questions
How do I horizontally flip an image in JavaScript using HTML5 Canvas?
Size the canvas to the image, translate the origin to the opposite edge, apply scale(-1, 1), then drawImage(image, 0, 0). For a horizontal mirror the translate is (canvas.width, 0); for a vertical flip it is (0, canvas.height) with scale(1, -1). The result is a real flipped bitmap that can be exported with toBlob().
What is the difference between CSS transform flip and Canvas flip for images?
CSS flipping changes only the on-screen presentation: the source bytes, the natural size, and any upload of img.src stay unchanged, which is why it is fine for a camera preview and wrong as a “fix and save” step. Canvas flipping redraws the pixels, so the result can be saved, uploaded, or passed into later document processing.
How can I batch flip or mirror scanned document images in a web application?
For multiple document pages, Dynamic Web TWAIN’s native Flip and Mirror methods operate directly on the scanned images in the buffer, so a hundred pages cost one call per page inside the SDK instead of a hundred canvas allocations and re-encodes in JavaScript.
What is the difference between flip and mirror in image editing?
They describe the same operation along different axes: “mirror” usually means horizontal (left to right, the selfie-camera axis) and “flip” usually means vertical (top to bottom, like turning a page over). Both are reflections, and both invert handedness, so mirrored text stays unreadable until it is reflected back.
Prerequisites
- A modern browser (Chrome, Firefox, or Edge) with HTML5 Canvas support
- Basic knowledge of JavaScript, HTML, and CSS
- Get a 30-day free trial license for Dynamic Web TWAIN if you want to use the SDK-based batch flip method
The Short Version
The pixel-level flip, without the tutorial wrapper:
function flipToCanvas(image, horizontal = true) {
const canvas = document.createElement("canvas");
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
const ctx = canvas.getContext("2d");
if (horizontal) {
ctx.translate(canvas.width, 0); // move the origin to the right edge
ctx.scale(-1, 1); // then draw right-to-left
} else {
ctx.translate(0, canvas.height); // origin at the bottom edge
ctx.scale(1, -1);
}
ctx.drawImage(image, 0, 0);
return canvas;
}
// flipToCanvas(img, false).toBlob((blob) => upload(blob), "image/jpeg", 0.92);
Three details decide whether this works: the canvas must match naturalWidth / naturalHeight rather than the CSS size, the translate must come before the scale, and the drawImage offsets stay at 0, 0 because the transform has already moved the origin. Setting canvas.width also resets the context, so calling the function repeatedly does not compound the transform.
The rest of this article builds the same logic into a page, starting from the interactive version.
Set Up an HTML5 Page for Image Flipping
Create a new HTML5 page with the following template and then let’s add the image flipping function to it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flip an Image with JavaScript</title>
<style>
</style>
</head>
<body>
<div class="home">
<h2>Flip an Image</h2>
<button id="flipButton">Flip</button>
</div>
<script>
</script>
</body>
</html>
Add a Direction Selector for Horizontal or Vertical Flip
We can flip an image in two directions: horizontal and vertical. We can add a select element to select which direction to use.
<label>
Direction:
<select id="directionSelect">
<option>Horizontal</option>
<option>Vertical</option>
</select>
</label>
Load an Image File into the Page
Add an input element for selecting files and use a button element to trigger it. The image file will be loaded into an image element.
HTML:
<button id="loadFileButton">Load a File</button>
<input style="display:none;" type="file" id="file" onchange="loadImageFromFile();" accept=".jpg,.jpeg,.png,.bmp" />
<div class="imageContainer">
<img id="image"/>
</div>
<style>
.imageContainer {
overflow: auto;
}
#image {
max-width: 50%;
}
</style>
JavaScript:
function loadImageFromFile(){
let fileInput = document.getElementById("file");
let files = fileInput.files;
if (files.length == 0) {
return;
}
let file = files[0];
fileReader = new FileReader();
fileReader.onload = function(e){
document.getElementById("image").src = e.target.result;
};
fileReader.onerror = function () {
console.warn('oops, something went wrong.');
};
fileReader.readAsDataURL(file);
}
Flip an Image Horizontally or Vertically Using CSS Transforms
We can use the CSS property transform to flip an HTML element like the following:
img.style.transform = "scaleY(-1)"; //flip vertically
img.style.transform = "scaleX(-1)"; //flip horizontally
img.style.transform = "scaleX(-1) scaleY(-1)"; //flip both vertically and horizontally
This is the standard fix for a front-facing camera preview, and the wrong fix for an upload: the pixels never move. The third line is the same result as rotate(180deg), which is a useful sanity check when a rotation and a flip disagree — rotating an image covers the angle side of the same transform.
Here is the code we use in the page to flip the image, which remembers the previous flipping status.
function flipImageWithCSS(){
let img = document.getElementById("image");
if (document.getElementById("directionSelect").selectedIndex == 0) {
if (img.style.transform.indexOf("scaleX") != -1) {
img.style.transform = img.style.transform.replace("scaleX(-1)","");
}else{
img.style.transform = img.style.transform+" scaleX(-1)";
}
}else{
if (img.style.transform.indexOf("scaleY") != -1) {
img.style.transform = img.style.transform.replace("scaleY(-1)","");
}else{
img.style.transform = img.style.transform+" scaleY(-1)";
}
}
}
Flip and Mirror an Image Using HTML5 Canvas 2D Context
HTML5 provides a canvas element which provides a way to manipulate image data. Unlike CSS which only changes the visual effect, we can use it to actually get a flipped image.
-
Add a hidden
canvaselement to the page.<canvas id="canvasHidden"></canvas> <style> #canvasHidden { display: none; } </style> -
Add a
selectelement to select which flipping method to use.<label> Method: <select id="methodSelect"> <option>CSS</option> <option>Canvas</option> </select> </label> -
Flip an image with
canvaswhen the selected method is “Canvas”.let method = document.getElementById("methodSelect").selectedIndex; if (method == 0) { flipImageWithCSS(); }else if (method == 1){ document.getElementById("image").style.transform = ""; flipImageWithCanvas(); }
Details of flipping an image with canvas.
-
Set the canvas’s size to match the image’s size.
const image = document.getElementById("image"); const canvas = document.getElementById("canvasHidden"); canvas.width = image.naturalWidth; canvas.height = image.naturalHeight; -
Get the context of the canvas to perform actions.
const context = canvas.getContext("2d"); -
Translate the
(0,0)to(width,0)and then scale the image using a scaling factor of -1 in the horizontal direction to flip the image horizontally. We can use a similar logic to flip the image vertically.if (document.getElementById("directionSelect").selectedIndex == 0) { context.translate(width, 0); context.scale(-1, 1); }else{ context.translate(0, height); context.scale(1, -1); } -
Use
drawImageto draw the image content.context.drawImage(image, 0, 0); -
Display the flipped image.
document.getElementById("image").src = canvas.toDataURL();
Batch Flip Document Images with Dynamic Web TWAIN
Dynamic Web TWAIN is a document scanning SDK making it possible to scan documents in the browser. It provides various image processing methods. We can use its Flip and Mirror methods to flip an image.
The advantage of using it is that it can be used to batch process a large volume of images as the processing is done using a native process.
Here are the steps to use it:
-
Include Dynamic Web TWAIN in the page.
<script src="https://unpkg.com/dwt@19.5.0/dist/dynamsoft.webtwain.min.js"></script> -
Initialize an instance of Web TWAIN and use it to flip the image; the license key from the prerequisites goes into
Dynamsoft.DWT.ProductKey.let DWObject; Dynamsoft.DWT.AutoLoad = false; Dynamsoft.DWT.ProductKey = "LICENSE-KEY"; Dynamsoft.DWT.ResourcesPath = "https://unpkg.com/dwt@19.5.0/dist"; async function flipImageWithWebTWAIN(){ if (!DWObject) { await initDWT(); } DWObject.RemoveAllImages(); let response = await fetch(document.getElementById("image").src); let buffer = await response.arrayBuffer(); DWObject.LoadImageFromBinary(buffer, function(){ if (document.getElementById("directionSelect").selectedIndex == 0) { DWObject.Mirror(0, function(){ //success document.getElementById("image").src = DWObject.GetImageURL(0); }, function(errorCode, errorString){ //fail console.log(errorString); }); }else{ DWObject.Flip(0, function(){ //success document.getElementById("image").src = DWObject.GetImageURL(0); }, function(errorCode, errorString){ //fail console.log(errorString); }); } }, function(errorCode, errorString){ console.log(errorString); }) } function initDWT(){ return new Promise((resolve, reject) => { const title = document.querySelector("h2").innerText; document.querySelector("h2").innerText = "Loading Dynamic Web TWAIN..."; Dynamsoft.DWT.CreateDWTObjectEx( { WebTwainId: 'dwtcontrol' }, function(obj) { DWObject = obj; document.querySelector("h2").innerText = title; resolve(); }, function(err) { console.log(err); document.querySelector("h2").innerText = "Failed to load Dynamic Web TWAIN"; reject(err); } ); }) }
Common Issues & Edge Cases
- Flipped image appears blank or half-empty: the
translateis missing or on the wrong side.scale(-1, 1)mirrors around the origin, so without moving the origin to the right edge everything lands outside the canvas. Horizontal needstranslate(width, 0), vertical needstranslate(0, height). - Blank or distorted output from
image.width: usenaturalWidthandnaturalHeight.image.widthreturns the rendered size, which is the CSS-scaled one. - CORS errors when calling
canvas.toDataURL(): if the image is loaded from a cross-origin URL, the canvas becomes tainted andtoDataURL()throws a security error. Serve images from the same origin or set thecrossOriginattribute on the<img>element before loading. - CSS flip does not persist after download: CSS
transformonly changes the visual rendering. If users need to save or upload the flipped result, use the Canvas method to produce actual pixel data viatoDataURL()ortoBlob(). - A mirrored scan is not a rotation problem. If the page reads backwards rather than sideways or upside-down, the source is one of the mirrored EXIF orientation values (2, 4, 5 or 7), or a scanner that produced a mirror image. Reflections cannot be undone by rotating — see EXIF orientation and browser behavior for the tag side, and auto-correcting scanned page orientation for the scanner side.
- High-DPI screenshots come out at half size. A canvas at
naturalWidthis a 1:1 copy of the source and ignoresdevicePixelRatio; that is correct for processing, but if the canvas is what the user sees on a 2× display, scale the context bydevicePixelRatioafter setting the size.
Related Guides
- Rotate an image in JavaScript — the angle counterpart, including why flipping both axes equals
rotate(180deg). - Resize an image before upload — the same canvas pipeline with A4 and ID card presets at 100–300 DPI.
- EXIF orientation: the 8 values and browser behavior — where mirrored photos come from, and what the browser has already done by the time you draw.
- Deskew a scanned document — when the page is crooked rather than mirrored.