Rotate and Save an Image using JavaScript and HTML5 canvas

← PrevNext →

You can rotate an image or any DOM element on your web page using CSS3 transform property. However, this property alone is not enough, if you want to save or download the rotated image. I am sharing an example here that shows how using HTML5 canvas properties and JavaScript, you can easily rotate and save (download) an image in your computer.

Rotate and Save image using JavaScript and Canvas

Note: I am using a little bit ES6 features in my example here.

<html>
<head>
    <title>Rotate and Save image in JavaScript</title>
</head>
<body>
    <p>Click the image to rotate 180 degrees and save</p>

    <img src="../../images/theme/bald-eagle.png" id="myimage" 
        onclick="rotateImage();" alt="" />
</body>

<script>
    let rotateImage = () => {
        let img = new Image();
        img.src = document.getElementById('myimage').src;
       
        // Create a canvas object.
        let canvas = document.createElement("canvas");
        
        // Wait till the image is loaded.
        img.onload = function(){
            rotateImage();
            saveImage(img.src.replace(/^.*[\\\/]/, ''));
        }
        
        let rotateImage = () => {
            // Create canvas context.
            let ctx = canvas.getContext("2d");	

            // Assign width and height.
            canvas.width = img.width;
            canvas.height = img.height;

            ctx.translate(canvas.width / 2,canvas.height / 2);

            // Rotate the image and draw it on the canvas. 
                // (I am not showing the canvas on the webpage.
            ctx.rotate(Math.PI);
            ctx.drawImage(img, -img.width / 2, -img.height / 2);
        }

        let saveImage = (img_name) => {
            let a = document.createElement('a');
            a.href = canvas.toDataURL("image/png");
            a.download = img_name;
            document.body.appendChild(a);
            a.click();        
        }
    }
        
</script>
</html>
Try it

The above script will rotate an image 180 degrees. Here, I am using the rotate() method of the "canvas" element.

ctx.rotate (Math.PI);

or

ctx.rotate(180 * Math.PI / 180);

Using the rotate() method you can rotate a drawing or an element at a given angle. The method takes a parameter, which is a number for the angle in radians. Here, in my example, I am using Math.PI as the parameter to rotate the image 180 degrees (or upside down).

If you want to rotate at 90 degrees angle, simply divide the Pi by 2.

cts.rotate (Math.PI / 2);

or, you can try this method.

ctx.rotate(90 * Math.PI / 180);

Along with the rotate() method, I have also used few other canvas methods such as,

1) traslate() method to position the image on the canvas.

2) drawImage() method to finally draw the image on the canvas.

Once I have completed drawing the image on the canvas, I’ll save or download the image.

let saveImage = (img_name) => { }

← PreviousNext →