How can I add a 3D tilt to a background image so that when you move the mouse the perspective of the image changes? I will be using this on an illustration of a piece of art on a wall in a gallery so I want it to tilt depending on where you mouse is as if you are viewing it from a different part of the room.
<style>
body {
background-image: url("https://c1.wallpaperflare.com/preview/442/138/421/art-gallery-canvas-arts-gallery.jpg");
background-position: 50% 50%;
height:100vh;
background-repeat:no-repeat;
}
</style>
<body>
By combining the css perspective
and transform
properties, we can achieve something like this
document.querySelector('.image-holder img').addEventListener('load', (event) => {
let cordinates = document.querySelector('.image-holder img').getBoundingClientRect();
let imageX = (cordinates.left + window.scrollX + cordinates.right) / 2;
let imageY = (cordinates.top + window.scrollY + cordinates.bottom) / 2;
const ANGLE_COMPENSATION = 10;
document.querySelector('.image-holder').addEventListener('mousemove', (event) => {
let mouseX = event.clientX;
let mouseY = event.clientY;
let xOffset = imageX - mouseX;
let yOffset = imageY - mouseY;
let xRotationAngle = yOffset / ANGLE_COMPENSATION;
let yRotationAngle = xOffset / ANGLE_COMPENSATION;
document.querySelector('.image-holder img').style.transform = "rotateX(" + xRotationAngle + "deg) rotateY(" + yRotationAngle + "deg) "
})
})
body .image-holder {
perspective: 2000px;
margin: 20px;
}
<div class="image-holder">
<img src="https://c1.wallpaperflare.com/preview/442/138/421/art-gallery-canvas-arts-gallery.jpg" />
</div>
Reduce the value of ANGLE_COMPENSATION
to increase senstivity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With