html 变换旋转在chrome中不能正常工作

y4ekin9u  于 2023-01-28  发布在  其他
关注(0)|答案(2)|浏览(126)

如果你变换rotate,它看起来可以工作,但是你必须移动鼠标光标到浏览器的左上方才能工作。我希望当我相对于蓝色正方形元素的中心移动鼠标光标时,它才能工作。我应该怎么做?

window.addEventListener("mousemove", (e) => {
  const card = document.querySelector(".card");
  const body = document.querySelector("body");

  const w = card.clientWidth;
  const h = card.clientHeight;
  
  const bodyRect = body.getBoundingClientRect();
  const cardRect = card.getBoundingClientRect();
  const left = cardRect.left - bodyRect.left + (card.clientWidth/2);
  const top = cardRect.top - bodyRect.top + (card.clientHeight/2);
  
  console.log(`cardRect.left : ${cardRect.left}, bodyRect.left : ${bodyRect.left}, card.clientWidth/2 : ${card.clientWidth/2}`);
  console.log(`cardRect.top : ${cardRect.top}, bodyRect.top : ${bodyRect.top}, card.clientHeight/2 : ${card.clientHeight/2}`);
  
  const rotx = (e.pageY - top) / e.pageY;
  const roty = (e.pageX - left) / e.pageX;
  
  console.log(`roty : ${roty}, rotx : ${rotx}`)
  
  card.style.msTransform = `rotateX(${rotx}deg) rotateY(${roty}deg)`;
  card.style.webkitTransform = `rotateX(${rotx}deg) rotateY(${roty}deg)`;
  card.style.transform = `rotateX(${rotx}deg) rotateY(${roty}deg)`;
});
.card {
  width: 400px;
  height: 400px;
  background-color: #00f;
  margin: 0 auto;
  padding: 0;
  transform-style: preserve-3d;
  transform: perspective(400px);
  will-change: transform;
}
<div class="card">
</div>
pepwfjgg

pepwfjgg1#

你的数学到处都是。看看你计算/log的旋转Angular ,它们几乎在整个屏幕上都〈5deg。

window.addEventListener("mousemove", (e) => {
  const card = document.querySelector(".card");
  
  const cardRect = card.getBoundingClientRect();
  const center = new DOMPoint(
    cardRect.x + cardRect.width/2,
    cardRect.y + cardRect.height/2
  );
  
  //turn 180deg/400px distance from the center
  const scale = 180/400;
  
  const rotY = (e.pageX - center.x) * scale; 
  const rotX = -(e.pageY - center.y) * scale;
  
  card.style.transform = `rotateX(${rotX}deg) rotateY(${rotY}deg)`;
});
.card {
  width: 400px;
  height: 400px;
  background-color: #00f;
  margin: 0 auto;
  padding: 0;
  transform-style: preserve-3d;
  transform: perspective(400px);
  will-change: transform;
}
<div class="card">
</div>
vql8enpb

vql8enpb2#

你的rotx和roty公式是错误的。试试这些:

const rotx = e.pageY - card.clientHeight / 2;
const roty = e.pageX - card.clientWidth / 2;

下面是一个片段来演示。
x一个一个一个一个x一个一个二个一个x一个一个三个一个

相关问题