The CSS transform property allows you to rotate an element on a web page. You can apply the transform property inside your JavaScript code to perform a task. Here in this post I am sharing a simple script showing how to rotate an Image on your web page using only JavaScript.

Related:

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.

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

The method rotate() takes a parameter in form of an angle, like, 90deg or 180deg etc (no spaces between 90deg). The deg denotes the degree. The value with the method rotate() will rotate an element in clock wise.

There are two ways 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.

<html> <head> <title>Rotate image using JavaScript</title> </head> <body> <p>Click on the image to rotate it 180 degrees clock wise.</p> <img src="../../images/theme/easy-image-resizer.jpg" id="myimage" onclick ="rotateImage();" alt="" /> </body> <script> function rotateImage() { var img = document. getElementById ('myimage'); img.style. transform = 'rotate(180deg)'; } </script> </html> Try it

Second Method

In this method, I have a class called .element defined in 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 my JavaScript code.

<html> <head> <title>Rotate image using JavaScript</title> <style> .element { transform: rotate(90deg); } </style> </head> <body> <p>Click on the image to rotate it 90 degrees clock wise.</p> <img src="../../images/theme/javascript.png" id="myimage" onclick ="rotateImage();" alt="" /> </body> <script> function rotateImage() { var img = document. getElementById ('myimage'); img. className = 'element'; } </script> </html> 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 →