Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 3D tilt a background image to change the perspective as you move the mouse?

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>
like image 853
gjjr Avatar asked Sep 16 '25 14:09

gjjr


1 Answers

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.

like image 182
Prakhar Avatar answered Sep 19 '25 06:09

Prakhar