我有一个方块跟随我的鼠标,其边框顶部是红色的以便看到旋转是否正确。我试图根据鼠标移动的角度来旋转它,比如如果鼠标向右上方移动45度,则方块必须旋转45度。问题在于,当我慢慢移动鼠标时,方块开始疯狂旋转。但如果我移动鼠标得足够快,方块旋转得很平滑。
实际上这只是我要完成的任务的一部分。我的整个任务是制作自定义圆形光标,在鼠标移动时拉伸。我要实现的想法是:按鼠标移动角度旋转圆形,然后将其进行scaleX操作以实现拉伸效果。但由于上述问题,我无法做到这一点。我需要我的跟随者在鼠标速度较慢时平稳旋转。
实际上这只是我要完成的任务的一部分。我的整个任务是制作自定义圆形光标,在鼠标移动时拉伸。我要实现的想法是:按鼠标移动角度旋转圆形,然后将其进行scaleX操作以实现拉伸效果。但由于上述问题,我无法做到这一点。我需要我的跟随者在鼠标速度较慢时平稳旋转。
class Cursor {
constructor() {
this.prevX = null;
this.prevY = null;
this.curX = null;
this.curY = null;
this.angle = null;
this.container = document.querySelector(".cursor");
this.follower = this.container.querySelector(".cursor-follower");
document.addEventListener("mousemove", (event) => {
this.curX = event.clientX;
this.curY = event.clientY;
});
this.position();
}
position(timestamp) {
this.follower.style.top = `${this.curY}px`;
this.follower.style.left = `${this.curX}px`;
this.angle = Math.atan2(this.curY - this.prevY, this.curX - this.prevX) * 180/Math.PI;
console.log(this.angle + 90);
this.follower.style.transform = `rotateZ(${this.angle + 90}deg)`;
this.prevX = this.curX;
this.prevY = this.curY;
requestAnimationFrame(this.position.bind(this));
}
}
const cursor = new Cursor();
.cursor-follower {
position: fixed;
top: 0;
left: 0;
z-index: 9999;
pointer-events: none;
user-select: none;
width: 76px;
height: 76px;
margin: -38px;
border: 1.5px solid #000;
border-top: 1.5px solid red;
}
<div class="cursor">
<div class="cursor-follower"></div>
</div>
if
条件中将0切换为1来检查自动移动(在上一个if
中将1切换为0)。 - Teemu