Sometimes we need to rotate the image on the web page, such as displaying the animation being loaded. In a document scanning web application, we need to rotate a document image with an tilted or scan incorrect direction.
In this article, we will discuss three ways to rotate images using JavaScript:
- Transform properties of CSS
- Canvas for HTML5
- Dynamic Web TWAIN, a document scan SDK
Write an HTML5 page to rotate the image
Let's write an HTML5 page to rotate the image.
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>
Loading pictures
Add to the file selectioninput
element and trigger it with buttons. The image will be loaded into two img elements, one for displaying the result of the rotation and the other for storing the original image.
HTML:
<button >Load a File</button> <input style="display:none;" type="file" onchange="loadImageFromFile();" accept=".jpg,.jpeg,.png,.bmp" /> <div class="imageContainer"> <img /> <img /> </div> <style> .imageContainer { max-width: 50%; } #image { max-width: 100%; } #imageHidden { display: none; } </style>
JavaScript:
function loadImageFromFile(){ let fileInput = ("file"); let files = ; if ( == 0) { return; } let file = files[0]; fileReader = new FileReader(); = function(e){ ("image").src = ; ("imageHidden").src = ; }; = function () { ('oops, something went wrong.'); }; (file); }
Rotate an image using CSS
We can use CSS propertiestransform
To rotate HTML elements, the usage is as follows:
= 'rotate(45deg)';
We can also specifytransform-origin
This property sets the origin of the rotation transformation. By default, the origin of the transformation is the center of the image.
Below are the specific implementations on the page.
Add to specify the rotation angleinput
element.
HTML:
<label for="degree">Degree (0-360):</label> <input type="number" name="degree" min="0" max="360" value="0"/>
monitorinput
Elementalchange
Event, rotate the image with CSS.
("degree").addEventListener("change",function(e){ const degree = ; rotateImage(degree); }) function rotateImage(degree){ const image = ("image"); const imageHidden = ("imageHidden"); if (!) { return; //no image selected } = ; = 'rotate(' + degree + 'deg)'; }
Using CSS does not actually change the image data, so the processing is fast. But it may have an overflow problem, which will cover other elements. We can set the overflow CSS property of its container toauto
to avoid obscuring other elements, but the image will be cut.
Rotate images using Canvas
HTML5 provides acanvas
Tags, we can use it to manipulate image data. We can use it to get the actual rotated image.
Add a hidden one to the pagecanvas
element.
<canvas ></canvas> <style> #canvasHidden { display: none; } </style>
Add oneselect
Element to select the rotation method to use.
<label> Method: <select > <option>CSS</option> <option>Canvas</option> </select> </label>
When the selected method is "Canvas", usecanvas
Rotate the image.
if (method == 0) { = ; = 'rotate(' + degree + 'deg)'; }else if (method == 1){ = ''; rotateImageWithCanvas(degree); }
Below we discuss how to use canvas to rotate images.
Gets the size of the new rotated image.
After rotation, the image will have a new size. We need to set the size of the canvas to match the size of the new image. Assuming we need to rotate the image around the center of the image, we can use the following function to calculate the new size.
First, get the four corner points and calculate their position after rotation. Then, based on these points, a positive peripheral rectangle is obtained.
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 < ; index++) { const point = points[index]; const rotatedPoint = getRotatedPoint(,,width/2,height/2,rad); if (minX == undefined) { minX = ; }else{ minX = (,minX); } if (minY == undefined) { minY = ; }else{ minY = (,minY); } maxX = (,maxX); maxY = (,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*/180 } ///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*(theta) - tempY*(theta); let rotatedY = tempX*(theta) + tempY*(theta); // translate back x = rotatedX + cx; y = rotatedY + cy; let point = {x:x,y:y}; return point; }
Set the size of canvas to the size of the rotated image.
const canvas = ("canvasHidden"); const imgWidth = ; const imgHeight = ; const rect = getBoundingRect(imgWidth,imgHeight,degree); = ; = ;
Get the context of canvas to perform the operation.
const ctx = ("2d");
usetranslate
Will new(0,0)
The origin position is set to the center of canvas.
(/2,/2);
userotate
Set the transformation matrix.
(Degree2Rad(degree));
usedrawImage
Draw the image content.
(imageHidden, -imgWidth/2, -imgHeight/2);
We need to specify the x-axis and y-axis coordinates of the upper left corner of the source image in the target canvas. Here, since the new origin is the center of canvas, we need to use-imgWidth/2
and-imgHeight/2
。
Displays the rotated image.
= ();
Rotate images using Dynamic Web TWAIN
Dynamic Web TWAIN is a document scanning SDK that allows you to scan documents in your browser. It provides various image processing methods. We can use itRotateExMethod to rotate the image.
The advantage of using it is that it can be used to batch process large numbers of images, as the processing is done using a local process.
Here are the steps to use it:
Introduce Dynamic Web TWAIN into the page.
<script src="/[email protected]/dist/"></script>
Add Dynamic Web TWAIN as the new rotation method.
<label> Method: <select > <option>CSS</option> <option>Canvas</option> <option>Dynamic Web TWAIN</option> </select> </label>
When it is selected as the rotation method, an instance of Web TWAIN is initialized and used to rotate the image. Can beHereApply for their license.
let DWObject; = false; = "DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ=="; //one-day trial = "/[email protected]/dist"; async function rotateImage(degree){ const method = ("methodSelect").selectedIndex; const image = ("image"); const imageHidden = ("imageHidden"); if (!) { return; } if (method == 0) { = ; = 'rotate(' + degree + 'deg)'; }else if (method == 1){ = ''; rotateImageWithCanvas(degree); }else if (method == 2){ = ''; if (!DWObject) { await init(); } rotateImageWithDWT(degree); } } function init(){ return new Promise((resolve, reject) => { const title = ("h2").innerText; ("h2").innerText = "Loading Dynamic Web TWAIN..."; ( { WebTwainId: 'dwtcontrol' }, function(obj) { DWObject = obj; ("h2").innerText = title; resolve(); }, function(err) { (err); ("h2").innerText = "Failed to load Dynamic Web TWAIN"; reject(err); } ); }) } function rotateImageWithDWT(degree){ return new Promise(async (resolve, reject) => { if (DWObject) { (); let file = ("file").files[0]; let buffer = await (); (buffer, function(){ const method = ("interpolationMethodSelect").selectedOptions[0].value; (0,degree,false,method, function(){ ("image").src = (0); }, function(errorCode, errorString){ reject(errorString); }); }, function(errorCode, errorString){ reject(errorString); }) }else{ reject(); } }) }
New pixels need to be added during rotation, called interpolation. Dynamic Web TWAIN provides several algorithms for this.
You can add oneselect
Elements are used to choose which algorithm to use.
<div class="dwtcontrols"> <label> Interpolation Method: <select > <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 the function of detecting the tilt angle of the document image. We can use it to determine the required rotation angle.
( 0, function(angle) { ("degree").value = 360+angle; rotateImage(360+angle); }, function(errorCode, errorString) { (errorString); } );
source code
All codes can be found in the following repository:
/tony-xlh/Rotate-Image-JavaScript
The above is the detailed introduction of the three methods of JavaScript to implement rotating images. For more information about JavaScript rotating images, please pay attention to my other related articles!