Canvas (HTML 5) Mouse Position

Want to know the position of the mouse pointer within your <canvas> element? Use jQuery? This code works in IE, Firefox, and Chrome:


$("#canvas_id").mousedown(function (event) {
var offset_x = event.pageX - $(this).offset().left;
var offset_y = event.pageY - $(this).offset().top;
// do something with the position
});

jQuery offers position() (which we don’t use) and offset() (which we use) to retrieve the position of an element relative to its enclosing element and the document, respectively. As jQuery also provides the position of the mouse relative to the document in the event.pageX properties, simple arithmentic is used to determine the offset within the element.

Want to play around with position data in mouse events? Try this:


$("#foo").mousemove(function (e) {
var pos = $(this).position();
var offset_x = e.pageX - $(this).offset().left;
var offset_y = e.pageY - $(this).offset().top;
console.log(e.pageX+","+e.pageY+" "+e.clientX+","+e.clientY+" off: "+e.offsetX+","+e.offsetY+" "+pos.top+","+pos.left+" "+e.layerX+","+e.layerY+" offset() "+$(this).offset().left+","+$(this).offset().top+" "+$(this).position().left+","+$(this).position().top+" offset = "+offset_x+","+offset_y);
});

Advertisements
This entry was posted in HTML 5, JavaScript, Software. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s