I’m fairly new to HTML5, but I’m learning, and for now – I’m working on a really simple game.
What I’m trying to do is get the mouse X and Y position related to the canvas, and have an image to follow the mouse (like a crosshair, to aim).
But for now, I just want to pull the mouse values.
So, I have a function called init, which initialises everything. It’s called when an image sprite is loaded:
function init(){
drawBg();
startDrawing();
document.addEventListener('keydown', checkKeyDown, false);
document.addEventListener('keyup', checkKeyUp, false);
document.addEventListener('ommousemove', mouseTarget, false);
}
I’m not 100% if the ‘ommousemove’ is correct, not sure what I’m suppose to put their. I then have the mouseTarget function:
function mouseTarget(e){
var mouseX;
var mouseY;
if(e.offsetX){
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if(e.layerX){
mouseX = e.layerX;
mouseY = e.layerY;
}
console.debug("Mouse X: " + mouseX + " Mouse Y: " + mouseY);
}
I also have a function called ‘draw’, which is called every 5 frames (every update), so I’m assuming I need to check the mouse position within that?
function draw(){
mouseTarget();
}
But then I get an error: Uncaught: TypeError: Cannot read property ‘offsetX’ of undefined.
What am I doing wrong here?
Thanks
The problem (as you suspected) is with this line
It should be
The
eparameter in themouseTargetfunction will only contain the event information when called via an event. In your case it is never being called via an event, but only via thedrawfunction.That is why you are getting the
Cannot read property 'offsetX' of undefined.error, as in reality you are trying to accessundefined.offsetXWhat you should do is keep a the mouse position in separate variables and then just reference them in the ‘draw’ function.