How to rotate an Image dynamically using JavaScript

← PrevNext →

The CSS transform property allows you to rotate an element on a web page. You can also use the transform property inside your JavaScript code to perform a task. Here in this post I'll show you how to use CSS transform property in JavaScript to rotate an image.

Syntax "transform"

transform: rotate(angle)

The transform property uses different values to perform different tasks like rotating, skewing, scaling, translating and moving etc. Some of its common values are rotate, scale, translate, skew and matrix.

In this example, I’ll use the rotate() method with the transform property inside my JavaScript code to rotate an image.

💡Do you know you can use rotate property (also) instead of "rotate()" method (to rotate an image) in JavaScript? Check this out.

The method rotate() takes a parameter in form of an angle, like, 90deg, 180deg etc (no spaces between 90deg).

There are two methods you can apply the transform property to the image through your JavaScript code.

First Method

In the first method I am assigning the rotate() method, with an angle, directly to the transform property. In-addition, I am using the image’s onclick event to call a function.

    <h2>Click on the image to rotate it 180 degrees clock wise.</h2>

    <img src="../../images/theme/easy-image-resizer.jpg" id="myimage" 
        onclick="rotateImage();" alt="" />

    let rotateImage = () => {
        let img = document.getElementById('myimage');
        img.style.transform = 'rotate(180deg)';
Try it
Second Method

In this method, I have a CSS class called .element defined inside the <style> section. The class has the transform property set with a default rotate value. I’ll simply assign the class to the image dynamically inside the JavaScript code.

        .element {
            transform: rotate(90deg);
    <h2>Click on the image to rotate it 90 degrees clock wise.</h2>

    <img src="../../images/theme/javascript.png" id="myimage" 
        onclick="rotateImage();" alt="" />
    let rotateImage = () => {
        var let = document.getElementById('myimage');
        img.className = 'element';
Try it

There may be other methods to rotate or manipulate an image dynamically. The examples that I have shared here, worked for me and its very simple. You can also use jQuery, if you to want further simplify it. However, I am comfortable with the above JavaScript example.

Well, now you know how to rotate an image on your webpage using plain JavaScript. You can also save the rotated image in your computer instantly. Read this post.

Browser Compatibility

I have checked the above examples using …

Microsoft Edge 85+ - Yes it worked
Firefox 62+ - Yes it worked
Chrome (any) - Yes it worked
Opera 56+ - Yes it worked

Thanks for reading. 🙂

← PreviousNext →