views:

39

answers:

3

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.

A: 

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 and mouseleave events on your canvas to enable/disable the mouse position capturing. That will reduce the of function calls.

hacksteak25
A: 
$('canvas').mousemove(function(e){
    drawPaddle(e.pageX, e.pageY);
});


function drawPaddle(paddleX, paddleY) {
    c.beginPath();
    c.rect(paddleX, paddleY, 150, 10);
    c.closePath();
    c.fill();
}
Ninja Dude
That's what I wanted to avoid tbh. I just wanted to grab the mouse co-ordinates from inside my `drawPaddle` function only. But it seems there is no other way.
Will
what is the event you're going to use to trigger the `drawPaddle()` or when are you going to call the `drawPaddle()`?
Ninja Dude
A: 

You will need to do

var where = {}
$('canvas').mousemove(function(e){
    where.x = e.pageX
    where.y = e.pageY;
});

and then use wherex,y in the function

mplungjan