In earlier posts, we’ve seen how you can enlarge or shrink an image on hover. In this post, you’ll learn how you can rotate an image on hover, by any specific degree you can want using Vue.js. It’s really easy using a reactive state which will be used as a boolean to check whether or not to bind a class which rotates the image. Here’s the code I’ve written to demonstrate the same:
<template>
<div id="app">
<div>
<img
:src="$options.imgUrl"
:class="{
'img-default': true,
'img-rotated': imageRotated,
}"
@mouseover="imageRotated = true"
@mouseout="imageRotated = false"
/>
</div>
<div class="np-credits">wwww.nightprogrammer.com</div>
</div>
</template>
<script>
export default {
name: "ImageRotated",
created() {
this.$options.imgUrl =
"https://media-cldnry.s-nbcnews.com/image/upload/rockcms/2022-01/220131-European-larch-trees-and-spruces-ew-512p-ec27db.jpg";
},
data() {
return {
imageRotated: false,
};
},
};
</script>
<style>
.img-default {
height: 300px;
transition: all 0.2s;
}
.img-rotated {
height: 300px;
transform: rotate(-10deg);
transition: all 0.2s;
}
.np-credits {
font-size: 12px;
margin-bottom: 12px;
color: #4b4b4b;
}
</style>
Code language: HTML, XML (xml)
In the above code, we’re fetching and binding an image to the img tag on line number 4. Now, whenever the user moves the mouse over the image, imageRotated state would be set to true. And whenever this is in true state, the CSS class img-rotated would get bind to the img tag. The img-rotated class has a transform property of rotation with -10 degrees. This will result in rotation of the image with a smooth 0.2 seconds of rotation transition.
You can find a working demo of the above code from my repos linked below: