如何使 x 轴和 y 轴上的鼠标位置值介于 -1 和 1 之间的值之间?

How can I make mouse position values on x & y axis range between to values between -1 & 1?

提问人:Emma Kitching 提问时间:4/27/2021 更新时间:4/27/2021 访问量:176

问:

我怎样才能使鼠标位置值而不是不规则值介于 -1 和 1 之间,有效地使屏幕中心等于 0,左边是 x -1,右边是 x 1,顶部 -1,底部 1?

var mouseX, mouseY;
jQuery(document).mousemove(function(e) {
    mouseX = e.pageX;
    mouseY = e.pageY;
    console.log('x', mouseX)
    console.log('y',mouseY)
}).mouseover(); 
jQuery 数学

评论


答:

0赞 MBo 4/27/2021 #1

您可以使用下一个公式:

x' = (2 * X - screenwidth) / screenwidth
y' = (2 * Y - screenheight) / screenheight

评论

0赞 Emma Kitching 4/27/2021
如何将其实现到我上面提供的代码中?
0赞 MBo 4/27/2021
我不知道 JQuery 说我们应该应用什么元素。也许?width()var width = $(window).width();
0赞 Emma Kitching 4/27/2021 #2
var windowWidth = jQuery(window).width();
var windowHeight = jQuery(window).height();
var mouseX, mouseY;
jQuery(document).mousemove(function(e) {
    mouseX = (e.pageX * 2 - windowWidth) / windowWidth;
    mouseY = (e.pageY * 2 - windowHeight) / windowHeight;
    console.log('x', mouseX)
    console.log('y', mouseY)
}).mouseover();
0赞 Ronald Bieber 4/27/2021 #3

MBo 和 Emma Kitching 的答案将产生浮动值。据我了解,您只在寻找 -1 或 1 的值。因此,仅使用条件语句会有所帮助。

var mouseX, mouseY;
jQuery(document).mousemove(function(e) {
    mouseX = e.clientX < $(window).width() / 2 ? -1 : 1;
    mouseY = e.clientY < $(window).height() / 2 ? -1 : 1;
    console.log('result: (x, y) = (' + mouseX + ', ' + mouseY + ')');
}).mouseover();

请注意,上面的代码使用浏览器窗口中的位置,而与滚动位置无关。如果要计算与完整页面及其大小相关的值,请改用 pageX/pageY 和页面大小。