We can use JavaScript to rotate an image easily by targeting the Style transform property and using the getElementById() method.
document.getElementById("image1").style.transform = "rotate(20deg)";
In the code above, you can change “20deg” to any degree amount you want to rotate the image by.
Let’s say we have the following HTML:
If we want to rotate the image by 90 degrees we can use the getElementById() method to target the image and then change its transform property in the following JavaScript code.
document.getElementById("image1").style.transform = "rotate(90deg)";
You can also rotate an image easily using jQuery.
Using JavaScript to Rotate an Image with a Click
To rotate an image using JavaScript, we can combine the getElementById() method with an onclick event.
In this example, we will have an image that we will want to rotate by 30 degrees. We will have a button that will allow the user to rotate the image by 30 degrees each time.
Here is our simple HTML code:
Rotate image
We can use an onclick event to run the function “rotateImage” when the user clicks a button.
We can then use the getElementById() method to target the transform property and use it to rotate our image.
Below is the JavaScript code which will allow the user to be able to rotate our image by 30degrees each time:
var rotateDegrees = 0;
function rotateImage(){
rotateDegrees += 30;
document.getElementById("image1").style.transform = "rotate(" + rotateDegrees + "deg)";
};
The final code and output for this example of how to use JavaScript to rotate an image is below:
Code Output:
Full Code:
Rotate image
<script>
var rotateDegrees = 0;
function rotateImage(){
rotateDegrees += 30;
document.getElementById("image1").style.transform = "rotate(" + rotateDegrees + "deg)";
};
</script>
Hopefully this article has been useful for you to understand how to use JavaScript to rotate an image.