How to Rotate an Image with JavaScript

1. Rotate the image counter-clockwise, 2. Customize image transform origin, 3. Rotate image on button click, 4. Rotate image incrementally.

Tari Ibaba
Coding Beauty Tutorials
4 min readAug 18, 2022

--

To rotate an image with JavaScript, access the image element with a method like getElementById(), then set the style.transform property to a string in the format rotate({value}deg), where {value} is the clockwise angle of rotation in degrees.

Consider this sample HTML:

index.html

Here’s how to easily rotate the #rotated image element from JavaScript:

index.js

And this will be the result on the web page:

First, we access the DOM element object with the document.getElementById() method.

Then, we use the style.transform property of the object to set the transform CSS property of the element from JavaScript.

We can specify any angle between 1 and 359 for the rotation:

Rotate Image Counter-Clockwise

We can rotate an image in the counter-clockwise direction by specifying a negative angle.

We can specify any angle between -1 and -359 degrees for counter-clockwise rotation.

Customize Image Transform Origin

We can use the transform-origin CSS property to set the point that the image will be rotated about. transform-origin is center by default, which means the element will be rotated about its center point.

In the following example, we rotate the image 90 degrees clockwise, as we did in the first example in this article.

But this time we customize the transform-origin property, so the image element ends up at a different position after the rotation.

Rotate Image on Button Click

To rotate the image at the click of a button, assign an event handler function to the onclick attribute of the button element.

For example:

index.html

Here the rotateImage() function serves as the click event handler. It contains the logic for rotating the image and will be called when the button is clicked.

index.js

Now when the button is clicked, the image will be rotated 90 degrees in the clockwise direction.

Rotate Image Incrementally

We can incrementally rotate the image on button click by storing the angle of rotation in a variable and using this variable to get and update the current angle. Many image editing apps allow you to rotate images in 90-degree angle increments.

index.js

Originally published at codingbeautydev.com

11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

Sign up and immediately receive a free copy.

--

--