使用 jQuery 获取鼠标坐标
我正在使用 jQuery 和 元素构建一个突破游戏。为了控制桨,它将跟随鼠标。所以我需要在我的
drawPaddle()
方法中获取鼠标坐标。
在 jQuery 网站上查看,它有这样的示例:
$(document).mousemove(function(e){
$('#status').html(e.pageX +', '+ e.pageY);
});
which do what I Want,但我不想像这样向我的项目添加另一个函数。这是我的 drawPaddle()
方法:
function drawPaddle() {
c.beginPath();
c.rect(paddleX, paddleY, 150, 10);
c.closePath();
c.fill();
// Get mouse position and update paddleX and paddleY here
}
因此,我需要找到一种方法来在调用 drawPaddle()
时获取鼠标位置,而不是在鼠标移动时获取鼠标位置类似 $(document).mousemove(function(e){ 的页面
确实如此。
如有任何帮助,我们将不胜感激,谢谢。
I am building a breakout game using jQuery and the <canvas>
element. To control the paddle, it will follow the mouse. So I need to get the mouse co-ordinates in my drawPaddle()
method.
Looking on the jQuery site it has examples like this:
$(document).mousemove(function(e){
$('#status').html(e.pageX +', '+ e.pageY);
});
Which does what I want, but I don't want to add another function to my project like this. This is my drawPaddle()
method:
function drawPaddle() {
c.beginPath();
c.rect(paddleX, paddleY, 150, 10);
c.closePath();
c.fill();
// Get mouse position and update paddleX and paddleY here
}
So I need to find a way to get the mouse position whenever the drawPaddle()
is called, and not whenever the mouse is moved on page like $(document).mousemove(function(e){
does.
Any help is appreciated, thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要执行
然后在函数中使用 wherex,y
You will need to do
and then use wherex,y in the function
我认为没有事件就没有办法做到这一点。我不知道 JavaScript 中没有任何字段可以全局存储该信息。前段时间我遇到了同样的问题,并使用
mousemove
事件解决了这个问题,因为我没有找到其他解决方案。也许某些浏览器实现了一种获取这些坐标的方法,但我不知道。但也许您可以在画布上使用
mouseenter
和mouseleave
事件来启用/禁用鼠标位置捕获。这将减少函数调用的次数。I think there is no way to do it without an event. I know no field in JavaScript that stores that information globally. Some time ago I had the same problem and did that with the
mousemove
event because I found no other solution. Maybe some browser implement a way to get those coordinates but I don't know.But maybe you can use
mouseenter
andmouseleave
events on your canvas to enable/disable the mouse position capturing. That will reduce the of function calls.