javascript 通过鼠标移动创建鼠标与屏幕中心的关联

fdx2calv  于 2023-05-21  发布在  Java
关注(0)|答案(1)|浏览(134)

我需要的div总是看着屏幕的中心,并沿着鼠标的位置移动一个小的距离说100 px

  • 鼠标在左中心-对象应该更左的鼠标位置和指向屏幕的中心
  • 鼠标在左上方-对象应该更左上方的鼠标位置和指向屏幕中心
  • 鼠标在右下角-对象应该更右下角的鼠标位置和指向屏幕中心

对于所有其他位置也是如此
我写了这个小代码,但我无法涵盖所有的情况。只有当你指向屏幕的顶部或右上方时,才可能有点效果😊
感谢你的帮助。如果你需要更多的细节,请告诉我

document.addEventListener('mousemove', (event) => {
  const deltaX = event.clientX - (myDiv.offsetLeft + myDiv.offsetWidth / 2);
  const deltaY = event.clientY - (myDiv.offsetTop + myDiv.offsetHeight / 2);

  const angle = Math.atan2(deltaY, deltaX) * (180 / Math.PI);

  const distance = 100; // Change this value to adjust the distance from the mouse

  const translateX = event.clientX - distance;
  const translateY = event.clientY - distance;

  myDiv.style.transform = `translate(${translateX}px, ${translateY}px) rotate(${angle}deg)`;
});
#myDiv {
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
  height: 100px;
  background-color: lightgray;
  transform-origin: center center;
  background: url(https://upload.wikimedia.org/wikipedia/commons/8/89/Flashlight.svg) no-repeat center / contain;
}
<div id="myDiv"></div>
xfyts7mz

xfyts7mz1#

给你,我已经改正了数学。如前所述,这个想法是首先将SVG(手电筒)指向页面的中心。现在计算从页面中心到给定坐标的Angular ,只需旋转正确指向的SVG或手电筒即可。
仅供参考,我已经删除了光标,并删除了卷轴的深入效果。

const centerX=window.innerWidth / 2;
const centerY=window.innerHeight/ 2;

document.addEventListener('mousemove', (event) => {
  const x = event.clientX;
  const y = event.clientY;
  const deltaX = (centerX - event.clientX);
  const deltaY = (centerY - event.clientY);
  
  let angle = Math.atan(deltaY/deltaX) * 180 / Math.PI;
  if((x>centerX && y<centerY) || (y>centerY && x>centerX))angle+=180
  
  const distance = 50; // Change this value to adjust the distance from the mouse

  const translateX = event.clientX - distance;
  const translateY = event.clientY - distance;
  
  const extraRotationForSVG = 210;

  myDiv.style.transform = `translate(${translateX}px, ${translateY}px) rotate(${angle+extraRotationForSVG}deg)`;
});
#myDiv {
  cursor:none;
  overflow:hidden;
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
  height: 100px;
  background-color: lightgray;
  transform-origin: center center;
  transform: rotate(-100deg);
  background: url(https://upload.wikimedia.org/wikipedia/commons/8/89/Flashlight.svg) no-repeat center / contain;
}
body{
  overflow:hidden;
}
<div id="myDiv"></div>

相关问题