gpt4 book ai didi

javascript - js/jq中检测鼠标向上、向左、向右、向下移动

转载 作者:行者123 更新时间:2023-12-01 00:21:54 26 4
gpt4 key购买 nike

我正在使用svg创建一个几何campass工具,其中有3个btns,1) 用于移动位于中心的整个营地2) 增加圆的半径3)用于旋转圆的半径4)根据第4个btn的位置使用路径(svg)绘制圆,该位置始终位于圆周上。

所以我有一个函数,

updateCircle(cx,cy,r, Angular )在此函数中,它查找所有 4btns 的位置和圆的半径(即 svg 中的线)以及大圆的半径和圆心

Circle欲了解更多信息,这里c1到c5是圆,l1是svg中的一条线 circle 2

对于第一个 btn,我使用当前光标在第一个 btn 上的 mousedown、mousemove 和 mouseup 移动点来更新圆圈位置。

默认 Angular 值为 90 度。

因此,对于第二个btn,我必须根据鼠标向下移动的情况增加半径,并在鼠标向上移动的情况下减小半径,当半径位于第三和第四象限时,当半径处于第三和第四象限时,则相反位于第一和第二象限。

所以问题来了:-

如何检测鼠标向上和向下移动?

或者有什么方法可以通过在第二个 btn 上执行任何 mousedown 和 mouse up 事件来执行增加和减少半径的操作吗?

第二个问题是:-

我如何创建第三个 btn 的功能(因为我确信我必须用 Angular 做一些事情,但有点困惑,比如当半径位于第三、第四象限并且鼠标向左移动时当鼠标向右移动时, Angular 增大;当半径位于第一和第二象限时, Angular 减小;反之亦然)

任何建议都应该受到赞赏和有值(value)。

最佳答案

检测鼠标移动方向

通过保留对前一个鼠标位置的引用,将其与新的位置进行比较,然后使用当前的鼠标位置更新下一次迭代的前一个鼠标位置,您可以轻松确定鼠标是向上还是向下移动。下面是如何在 JavaScript 中实现这一点的示例:

const lastPoint = {x: null, y: null}
window.addEventListener('mousemove', e => {
const leftOrRight = (
e.clientX > lastPoint.x ? 'right'
: e.clientX < lastPoint.x ? 'left'
: 'none'
)
const upOrDown = (
e.clientY > lastPoint.y ? 'down'
: e.clientY < lastPoint.y ? 'up'
: 'none'
)

/*
here you can apply the transformations you need to,
then update the cursor position tracker for the
next iteration
*/

lastPoint.x = e.clientX
lastPoint.y = e.clientY
})

旋转

假设您正在使用 CSS 转换,您可以跟踪 javascript 中的旋转变量并将其动态应用到 DOM 元素的内联 CSS。使用与上述相同的方法,您可以在鼠标向上移动时向一种方向旋转,而在向下移动时向另一种方向旋转。以下是如何实现这一点。

圆.html

<div class="circle" style="transform: rotate(0deg);"><div class="inner"></div></div>

圆.css

.circle {
width: 100px;
height: 100px;
background-color: green;
border-radius: 50%;
position: relative;
}

.circle .inner {
width: 10px;
height: 10px;
background-color: orange;
border-radius: 50%;
margin: auto;
}

旋转.js

const rotatingCircle = document.getElementsByClassName('circle')[0]

const lastPoint = {x: null, y: null}
let rotation = 0
window.addEventListener('mousemove', e => {
rotation += (
e.clientY > lastPoint.y ? -1
: e.clientY < lastPoint.y ? 1
: 0
)

rotatingCircle.style = `transform: rotate(${rotation}deg);`

lastPoint.x = e.clientX
lastPoint.y = e.clientY
})

在此处查看实时旋转示例:https://codepen.io/OneCent/pen/jOEMpEr

如果这有帮助或者您有任何疑问,请告诉我!

关于javascript - js/jq中检测鼠标向上、向左、向右、向下移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59341675/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com