Rotation is a two-dimensional transformation that is used to change the orientation of an object.
There are many ways to rotate images using CSS. The most common way to rotate image is to use the CSS rotation property. This property allows you to rotate an image by a certain degree.
You can also use the rotate css function. This function allows you to rotate an image by a certain degree.
Learning Objectives
In this lecture you will learn:
- Css rotate proprty
- Create a button and an image to rotate image
- Rotate image using javascript
- Summary
CSS Rotate property
#gearImage {
animation: rotation 1s linear 0s infinite;
animation-play-state: paused;
}
@keyframes rotation {
to {
transform: rotate(360deg)
}
}
Create a button and an image to rotate image
<img id="gearImage" src="https://icon2.cleanpng.com/20180204/vee/kisspng-gear-icon-gears-png-file-5a7793b1e283d3.8984860115177860339278.jpg" height="100"></br>
</br>
<button onclick="rotateImage()">toogle rotation</button>
Rotate image using javascript
Here is the javascript code to rotate image. We have webKitAnimationPlayState that will make things easy you can check the state of the element and change the state to paused or running and it will help to rotate image.
<script>
function rotateImage() {
var image = document.getElementById("image");
if (image.style.webkitAnimationPlayState == "running") {
image.style.webkitAnimationPlayState = "paused";
} else {
image.style.webkitAnimationPlayState = "running";
}
}
</script>
Here is the complete Code to rotate image using javascript
<!DOCTYPE html>
<html>
<head>
<style>
#gearImage {
animation: rotation 1s linear 0s infinite;
animation-play-state: paused;
}
@keyframes rotation {
to {
transform: rotate(360deg)
}
}
</style>
</head>
<body>
<style>
<img id="gearImage" src="https://icon2.cleanpng.com/20180204/vee/kisspng-gear-icon-gears-png-file-5a7793b1e283d3.8984860115177860339278.jpg" height="100"></br>
</br>
<button onclick="rotateImage()">toogle rotation</button>>
<script>
function rotateImage() {
var image = document.getElementById("gearImage");
if (image.style.webkitAnimationPlayState == "running") {
image.style.webkitAnimationPlayState = "paused";
} else {
image.style.webkitAnimationPlayState = "running";
}
}
</script>
</body>
</html>
If you want to rotate image to some angle that you want then you just have to change the property transform and provide it some value in angle like that
<script>
function rotateImg() {
document.querySelector("#img").style.transform = "rotate(90deg)";
}
</script>