使用 Javascript 变换动画

Transform animation with Javascript

我制作动画来响应 mousemove 事件侦听器,但是框旋转原点似乎不在中间框的中心并且它不能 rotate/tilt 到左和上。

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>

它不能向左和向上旋转,只能向右和向下旋转。任何人都知道如何使其 rotate/tilt 向左或向上并使原点居中?

尝试将 transform-origin 更改为 50%

transform-origin:50%;

给你(如果下面的效果不满足你也可以使用vanilla-tilt js):

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>