How to Rotate an Image in JavaScript: CSS, Canvas, SDK
Rotating an image in JavaScript is either a paint operation or a pixel operation, and picking the wrong one is why rotated images sometimes arrive at the server unrotated. element.style.transform = 'rotate(90deg)' changes what the browser shows and nothing else; a canvas translate / rotate / drawImage sequence rewrites the pixels so the result can be uploaded, OCR’d, or printed.
For the common case — a page that has to be turned by 90° — the pixel path is four lines on a canvas whose width and height are swapped: ctx.translate(canvas.width, 0), ctx.rotate(Math.PI / 2), ctx.drawImage(image, 0, 0), then export with toBlob(). Anything that is not a multiple of 90° also needs a canvas sized to the rotated bounding box, which is the function in The Short Version below.
This article covers both paths, plus the SDK route for scanned pages: CSS for previews, canvas for a rotated file, and Dynamic Web TWAIN’s RotateEx for batch rotation with a deskew angle detected by the SDK rather than guessed by the user.
What you’ll build: An HTML5 page that rotates images three ways — CSS transform, HTML5 Canvas, and Dynamic Web TWAIN — with arbitrary angles, selectable interpolation, and automatic skew detection for scanned documents.
Key Takeaways
- CSS
transform: rotate()is display-only. Canvasctx.rotate()plusdrawImage()produces a new bitmap, which is what you need before upload, OCR, or PDF generation. - A canvas rotation needs three things, in this order: a canvas sized to the rotated bounding box,
ctx.translate()to move the origin to the centre, andctx.rotate()before drawing with the source offset by half its width and height. - For 90°, 180° and 270° the bounding box is exact — swap width and height and nothing else. For arbitrary angles, the rotated bounding box has to be computed from the four transformed corners.
- Dynamic Web TWAIN’s
RotateExruns rotation in a native process, accepts an interpolation method (nearest neighbour through bicubic), and pairs withGetSkewAngleso a scanned page can be straightened without user input. - The browser has already applied any EXIF orientation tag by the time you draw, so rotating by the tag value as well is the usual cause of a page that lands 90° off.
Common Developer Questions
How do I rotate an image by a custom angle in JavaScript without losing quality?
Draw it into a canvas sized to the rotated bounding box: compute the four corner positions after rotation, size the canvas to their extents, translate the origin to the canvas centre, call ctx.rotate(angle), then drawImage at -width/2, -height/2. Quality is decided at export time — use toBlob('image/jpeg', 0.92) or PNG rather than the default lossy path, and avoid rotating an already-compressed copy more than once.
How can I auto-detect and fix a skewed document image in the browser?
Dynamic Web TWAIN detects the angle for you with GetSkewAngle and then applies it with RotateEx, which is the practical route for batches of scanned pages because nobody is going to type the angle for every page. The detection reads the document’s text baseline, so it works on text pages rather than on photos.
What is the difference between rotating an image with CSS and rotating with Canvas?
CSS rotation only changes how the image is displayed: img.src is untouched, naturalWidth is unchanged, and a download or upload of the source gets the original bytes. Canvas rotation redraws the pixels into a new bitmap, so the rotated result can be saved, uploaded, or fed into OCR.
Does rotating with canvas change the image file’s EXIF orientation?
No. The canvas has no EXIF block, so the exported file carries only new pixel data — that is why a canvas rotation is also a reliable way to bake an EXIF orientation into the pixels. If the browser already applied the tag, do not rotate again by the tag value.
Prerequisites
To follow along, you need a modern browser (Chrome, Firefox, Edge, or Safari) and a text editor. To use the Dynamic Web TWAIN approach in Step 5, get a 30-day free trial license for Dynamic Web TWAIN.
The Short Version
If you only need the rotation and not the tutorial, this is the whole pixel-level operation. It rotates by any angle and returns a canvas you can export with toBlob():
function rotateToCanvas(image, degrees) {
const rad = (degrees * Math.PI) / 180;
const w = image.naturalWidth;
const h = image.naturalHeight;
// Bounding box of the rotated corners.
const cos = Math.abs(Math.cos(rad));
const sin = Math.abs(Math.sin(rad));
const outW = Math.round(w * cos + h * sin);
const outH = Math.round(w * sin + h * cos);
const canvas = document.createElement("canvas");
canvas.width = outW;
canvas.height = outH;
const ctx = canvas.getContext("2d");
ctx.translate(outW / 2, outH / 2); // origin at the centre
ctx.rotate(rad); // turn the grid
ctx.drawImage(image, -w / 2, -h / 2); // centre the image on that origin
return canvas;
}
// rotateToCanvas(img, 90).toBlob((b) => upload(b), "image/jpeg", 0.92);
For multiples of 90° the bounding box above is exact, so the same function handles the common “rotate the page” case without a special branch. The rest of the article builds this up step by step, then adds the two paths that are better suited to document work: native batch rotation and skew detection.
In this article, we are going to talk about three ways to rotate an image with JavaScript:
- CSS’s Transform Property
- HTML5’s Canvas
- Dynamic Web TWAIN, a document-scanning SDK
Build an HTML5 Page to Rotate Images
Let’s build an HTML5 page to do this.
Step 1: Create a New HTML File
Create a new HTML file with the following template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rotate an Image with JavaScript</title>
<style>
.home {
display: flex;
align-items: center;
flex-direction: column;
}
</style>
</head>
<body>
<div class="home">
<h2>Rotate an Image</h2>
</div>
<script></script>
</body>
</html>
Step 2: 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 two image elements, one for displaying the rotated result and one for storing the original image.
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"/>
<img id="imageHidden"/>
</div>
<style>
.imageContainer {
max-width: 50%;
}
#image {
max-width: 100%;
}
#imageHidden {
display: none;
}
</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;
document.getElementById("imageHidden").src = e.target.result;
};
fileReader.onerror = function () {
console.warn('oops, something went wrong.');
};
fileReader.readAsDataURL(file);
}
Step 3: Rotate an Image Using CSS Transform
We can use the CSS property transform to rotate an HTML element like the following:
element.style.transform = 'rotate(45deg)';
We can also specify the transform-origin CSS property to set the origin of the rotation transform. By default, the origin of a transform is center which we will use.
Let’s implement it in the page.
-
Add an
inputelement for specifying the rotation angle.HTML:
<label for="degree">Degree (0-360):</label> <input type="number" id="degree" name="degree" min="0" max="360" value="0"/> -
Listen to the
changeevent of theinputelement to rotate the image with CSS.document.getElementById("degree").addEventListener("change",function(e){ const degree = e.target.value; rotateImage(degree); }) function rotateImage(degree){ const image = document.getElementById("image"); const imageHidden = document.getElementById("imageHidden"); if (!image.src) { return; //no image selected } image.src = imageHidden.src; image.style.transform = 'rotate(' + degree + 'deg)'; }
Using CSS does not actually change the image data, so its processing speed is good. But it may have an overflow problem blocking other elements. We can set the overflow CSS property of its container to auto to avoid blocking other elements but the image will be cut.
Step 4: Rotate an Image Using HTML5 Canvas
HTML5 provides a canvas element which provides a way to manipulate image data. We can use it to actually get a rotated image.
-
Add a hidden
canvaselement to the page.<canvas id="canvasHidden"></canvas> <style> #canvasHidden { display: none; } </style> -
Add a
selectelement to select which rotating method to use.<label> Method: <select id="methodSelect"> <option>CSS</option> <option>Canvas</option> </select> </label> -
Rotate an image with
canvaswhen the selected method is “Canvas”.if (method == 0) { image.src = imageHidden.src; image.style.transform = 'rotate(' + degree + 'deg)'; }else if (method == 1){ image.style.transform = ''; rotateImageWithCanvas(degree); }
Let’s now talk about how to actually rotate an image with canvas.
-
Get the new size of the rotated image.
After rotation, the image will have a new size. We have to set the canvas’s size to match the new size. Suppose we need to rotate an image around its center, we can have to following functions to calculate the new size.
First, get the four corner points and calculate their positions after rotation. Then, get the bounding rect based on the points.
function getBoundingRect(width,height,degree) { let rad = Degree2Rad(degree); let points = [{x:0,y:0},{x:width,y:0},{x:width,y:height},{x:0,y:height}]; let minX = undefined; let minY = undefined; let maxX = 0; let maxY = 0; for (let index = 0; index < points.length; index++) { const point = points[index]; const rotatedPoint = getRotatedPoint(point.x,point.y,width/2,height/2,rad); if (minX == undefined) { minX = rotatedPoint.x; }else{ minX = Math.min(rotatedPoint.x,minX); } if (minY == undefined) { minY = rotatedPoint.y; }else{ minY = Math.min(rotatedPoint.y,minY); } maxX = Math.max(rotatedPoint.x,maxX); maxY = Math.max(rotatedPoint.y,maxY); } let rectWidth = maxX - minX; let rectHeight = maxY - minY; let rect = { x: minX, y: minY, width: rectWidth, height: rectHeight } return rect; } function Degree2Rad(degree){ return degree*Math.PI/180 } //https://gamedev.stackexchange.com/questions/86755/how-to-calculate-corner-positions-marks-of-a-rotated-tilted-rectangle function getRotatedPoint(x,y,cx,cy,theta){ let tempX = x - cx; let tempY = y - cy; // now apply rotation let rotatedX = tempX*Math.cos(theta) - tempY*Math.sin(theta); let rotatedY = tempX*Math.sin(theta) + tempY*Math.cos(theta); // translate back x = rotatedX + cx; y = rotatedY + cy; let point = {x:x,y:y}; return point; } -
Set the canvas’s size as the rotated image’s size.
const canvas = document.getElementById("canvasHidden"); const imgWidth = imageHidden.naturalWidth; const imgHeight = imageHidden.naturalHeight; const rect = getBoundingRect(imgWidth,imgHeight,degree); canvas.width = rect.width; canvas.height = rect.height; -
Get the context of the canvas to perform actions.
const ctx = canvas.getContext("2d"); -
Use
translateto set the new(0,0)position as the center of the canvas.ctx.translate(canvas.width/2,canvas.height/2); -
Use
rotateto set the transformation matrix.ctx.rotate(Degree2Rad(degree)); -
Use
drawImageto draw the image content.ctx.drawImage(imageHidden, -imgWidth/2, -imgHeight/2);We need to specify the x-axis and y-axis coordinates in the destination canvas at which to place the top-left corner of the source image. So here, since the new origin is the center of the canvas, we need to use
-imgWidth/2and-imgHeight/2. -
Display the rotated image.
document.getElementById("image").src = canvas.toDataURL();
Step 5: Rotate and Deskew 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 RotateEx method to rotate 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> -
Add Dynamic Web TWAIN as a new rotation method.
<label> Method: <select id="methodSelect"> <option>CSS</option> <option>Canvas</option> <option>Dynamic Web TWAIN</option> </select> </label> -
When it is selected as the method for rotation, initialize an instance of Web TWAIN and use it to rotate 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 rotateImage(degree){ const method = document.getElementById("methodSelect").selectedIndex; const image = document.getElementById("image"); const imageHidden = document.getElementById("imageHidden"); if (!image.src) { return; } if (method == 0) { image.src = imageHidden.src; image.style.transform = 'rotate(' + degree + 'deg)'; }else if (method == 1){ image.style.transform = ''; rotateImageWithCanvas(degree); }else if (method == 2){ image.style.transform = ''; if (!DWObject) { await init(); } rotateImageWithDWT(degree); } } function init(){ 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); } ); }) } function rotateImageWithDWT(degree){ return new Promise(async (resolve, reject) => { if (DWObject) { DWObject.RemoveAllImages(); let file = document.getElementById("file").files[0]; let buffer = await file.arrayBuffer(); DWObject.LoadImageFromBinary(buffer, function(){ const method = document.getElementById("interpolationMethodSelect").selectedOptions[0].value; DWObject.RotateEx(0,degree,false,method, function(){ document.getElementById("image").src = DWObject.GetImageURL(0); }, function(errorCode, errorString){ reject(errorString); }); }, function(errorCode, errorString){ reject(errorString); }) }else{ reject(); } }) } -
New pixels have to be added during rotation which is called interpolation. Dynamic Web TWAIN provides several algorithms to do this.
A
selectelement is added for this.<div class="dwtcontrols"> <label> Interpolation Method: <select id="interpolationMethodSelect"> <option value="1">Nearest Neighbour</option> <option value="2">Bilinear</option> <option value="3">Bicubic</option> <option value="5" selected>Best Quality</option> </select> </label> </div> -
Web TWAIN also has a function to detect the skew angle of a document image. We can use it to determine the angle for rotation. A skewed scan is the case this exists for: the page was fed at an angle of a few degrees, so a fixed 90° rotation does not help.
DWObject.GetSkewAngle( 0, function(angle) { document.getElementById("degree").value = 360+angle; rotateImage(360+angle); }, function(errorCode, errorString) { console.log(errorString); } );
Common Issues & Edge Cases
- EXIF orientation ignored: JPEG photos from phones often embed EXIF orientation data. In current Chromium the tag has already been applied by the time
drawImageruns, so the image arrives upright and the canvas size matchesnaturalWidth/naturalHeight. Rotating by the tag value on top of that is what produces a page that is 90° off or mirrored — see how browsers handle EXIF orientation. - Canvas
toDataURLre-encodes as PNG by default. For large photos this produces very large files. Pass'image/jpeg'and a quality value (e.g.,canvas.toDataURL('image/jpeg', 0.92)) to keep file size manageable. - CSS rotation overflows its container. Rotating by non-90° angles can push the image outside its parent div, overlapping other elements. Set
overflow: auto(orhidden) on the container and be aware that the image may be clipped. - Fractional canvas sizes blur the result.
canvas.widthtruncates to an integer, so a 45° rotation of an odd-sized image loses a pixel of the bounding box and the edges smear. UseMath.roundon the computed extents, and if the page is a document, prefer 90° steps where the bounding box is exact. - Rotating a mirrored image looks like rotating a normal one. If the output reads backwards, the input is one of the mirrored EXIF values, not a rotation problem.
Related Guides
- Flip and mirror an image in JavaScript — the four mirror axes, and why a flipped page reads backwards.
- Resize an image before upload — the same canvas pipeline with document presets (A4 and ID card at 100–300 DPI).
- EXIF orientation: the 8 values and browser behavior — the tag that makes a rotated image arrive upright whether you asked for it or not.
- Auto-correct scanned document orientation — scanner-side rotation and OCR-based detection for pages fed upside-down.