JavaScript: How to Rotate Images

This tutorial will cover how to rotate images with JavaScript and the CSS transform: rotate() property.

 

Create an HTML Image

Let's begin by creating an img element in our HTML. It will have an ID so we can access it easily in JavaScript and a src attribute referencing an image.

 

<!DOCTYPE html>
<html>
<head>
  <title>Test</title>
  <link rel="stylesheet" type="text/css" href="style.css">

</head>
<body>

<img class="foo" src="https://www.skillsugar.com/media/image/thumb/if-not-1634165908.png">

</body>
<script src="app.js"></script>
</html>

 

Rotate HTML Image 90 Degrees

Let's rotate the image 90 degrees using the transform: rotate(); CSS property. To do this we will define a CSS class selector, then add it to the img element with JavaScript.

 

./style.css
.rotated {
  transform: rotate(90deg);
}

 

./app.js
var elm = document.getElementById('foo');

elm.classList.add('rotated');

 

 

The rotation value is an angular unit of degrees, which means we can use a value between 0 and 359 to rotate the image.

 

JavaScript On Click Rotate Image Function

Now we know how to rotate an image, let's create a reusable rotate JavaScript function. It will take two arguments; the element to rotate and degrees of rotation. For our example, we will call this function when an image with a particular class is clicked.

 

<img class="foo" src="https://www.skillsugar.com/media/image/thumb/if-not-1634165908.png">
function rotate(element, rotation = 90) {
  element.style.transform = 'rotate(' + rotation + 'deg)';
}

document.querySelector('.foo').addEventListener('click', function() {
  rotate(this, 145);
});

 

As you can see in the example above function, rotation has a default value of 90, which means if we don't supply a second argument it will default to that value.

 

function rotate(element, rotation = 90) {
  element.style.transform = 'rotate(' + rotation + 'deg)';
}

document.querySelector('.foo').addEventListener('click', function() {
  rotate(this);
});

 

Rotate an Image Counterclockwise

Another thing to mention is you can supply a negative value to the transform: rotate() property to rotate counterclockwise. Here is an example of that using the function we just created:

 

function rotate(element, rotation = 90) {
  element.style.transform = 'rotate(' + rotation + 'deg)';
}

document.querySelector('.foo').addEventListener('click', function() {
  rotate(this, -90);
})