I make Animation to response mousemove event listener, but the box rotate origin seems like not centered at a middle box and it cant rotate/tilt to left & top.
const box = document.querySelector('#box');
box.addEventListener('mousemove', function(event) {
const middleX = this.clientWidth / 2;
const middleY = this.clientHeight / 2;
const layX = -(event.layerY / 7);
const layY = (event.layerX / 7);
this.style.transformOrigin = `${middleX}px ${middleY}px`;
this.style.transform = `rotateX(${layX}deg) rotateY(${layY}deg)`;
});
* {
margin: 50px;
padding: 0;
}
.container {
perspective: 1000px;
background-color: rgb(105, 105, 105);
display: flex;
align-items: center;
justify-content: center;
border: 2px solid black;
}
#box {
height: 200px;
width: 200px;
background-color: rgb(0, 255, 255);
border-radius: 20%;
transition: 0.3s ease;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Animation MouseMove</title>
</head>
<body>
<div class="container">
<div id="box"></div>
</div>
</body>
</html>
It cant rotate to left & top, just can rotate to right & bottom. Anyone know how to make it rotate/tilt to left or top and make centered origin?
CodePudding user response:
Try changing transform-origin
to 50%
transform-origin:50%;
CodePudding user response:
Here you go(you can also use vanilla-tilt js if the effect below not satisfying you):
const box = document.querySelector(".box");
const container = document.querySelector(".container");
let sensitivity = 5;
container.addEventListener("mousemove", (event) => {
let osX = (window.innerWidth / 2 - event.pageX) / sensitivity ;
let osY = (window.innerHeight / 2 - event.pageY) / sensitivity ;
box.style.transform = `rotateY(${osX}deg) rotateX(${osY}deg)`;
});
body{
height: 100vh;
display:flex;
align-items: center;
justify-content:center;
flex-direction: column;
perspective: 1000px;
}
*{
margin:0;
padding:0;
box-sizing: border-box;
}
.container{
display:flex;
align-items: center;
justify-content:center;
background: blue;
width: 800px;
height: 800px;
}
.box{
border: 5px solid yellow;
transform-origin: center;
width: 200px;
height: 200px;
background: red;
transform-style: preserve-3d;
display:flex;
align-items: center;
justify-content:center;
color: #fff;
font-family: verdana;
border-radius: 20%;
}
<div class="container">
<div class="box">
Hello World!
<div>
</div>