How to Rotate Images using JavaScript

Updated onbyAlan Morel
How to Rotate Images using JavaScript

JavaScript's built-in APIs give you powerful control over the user interface and experience that your visitors get.

One of the coolest things you can do using JavaScript is take an existing image on the page and rotating it.

In this post, we'll learn how to rotate an image using JavaScript.

How to Rotate an Image Using JavaScript

To learn how to rotate an image using JavaScript, we'll use the following HTML:

HTML
<html> <head> <title>Rotate an Image Using JavaScript</title> </head> <body> <img id="image" src="https://placeimg.com/640/480/any" /> </body> </html>

That looks like this:

  • HTML

Remember that to place an image, use the <img> tag. The src attribute sets the URL the browser will fetch the data from.

Now, to rotate this image, first we must query the DOM for it.

We can do this using the document.querySelector() method.

JAVASCRIPT
const image = document.querySelector("#image");

Once we have the image, we can then rotate it using the style.transform property, and call the rotate() method.

The rotate() method takes a single argument, which is the angle you want to rotate the image by.

Let's say you want to rotate it by 90 degrees. You can do this by passing in the string "90deg".

JAVASCRIPT
const image = document.querySelector("#image"); image.style.transform = "rotate(90deg)";

Now, to test this code out, we can create a button to trigger this action.

Add a button to your markup:

HTML
<html> <head> <title>Rotate an Image Using JavaScript</title> </head> <body> <button id="rotate">Rotate</button> <br> <img id="image" src="https://placeimg.com/640/480/any" /> </body> </html>

Now, we can query the DOM for the button and add an event listener to it that will rotate the image when pressed:

JAVASCRIPT
const image = document.querySelector("#image"); const button = document.querySelector("#rotate"); button.addEventListener("click", () => { image.style.transform = "rotate(90deg)"; });

Here's the final code:

HTML
<html> <head> <title>Rotate an Image Using JavaScript</title> </head> <body> <button id="rotate">Rotate</button> <br> <img id="image" src="https://placeimg.com/640/480/any" /> <script> const image = document.querySelector("#image"); const button = document.querySelector("#rotate"); button.addEventListener("click", () => { image.style.transform = "rotate(90deg)"; }); </script> </body> </html>
  • HTML
  • JavaScript

Conclusion

In this post, we learned how to rotate an image using JavaScript.

Simply query the DOM for the image, and then use the style.transform property to rotate it by the angle that you desire.

Thanks for reading and happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.