I’m working on a canvas, and now I’ve reached the point where I need to find the mouse’s coordinates so I can make “buttons” inside said canvas. However, when I try to capture the coordinates and use them in a function to determine if the mouse is inside the button, it doesn’t work.
What’s wrong with my coordinate retrieval method? This is for a game my friend and I are making for a school project.
Here’s the code:
<!-- game canvas -->
<canvas id="canvas" width="900" height="600">
<!-- no-support message -->
Se está a ver isto, o seu browser não suporta HTML5.
</canvas>
Just the canvas because nohing else really matters.
Here’s the javascript:
//find mouse coordinates
var mouseX = 0, mouseY = 0;
$('#canvas').mousemove(function(e){
mouseX = e.pageX - this.offsetLeft;
mouseY = e.pageY - this.offsetTop;
});
varcreates a local variable. In your case, however, you want to update the variables outside the function instead of creating new local ones. So, just dropvarinside themousemovefunction.Currently, the outside variables are “shadowed” by the local variables, and have become inaccessible.
http://jsfiddle.net/wXMyH/1/