Question

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.

Was it helpful?

Solution

$('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();
}

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top