dyenair
dyenair

Reputation: 23

Drawing pointer(mouse coordinates) for canvas of HTML5

I'm having trouble in mouse coordinates when drawing at canvas of HTML5. I'm using JavaScript to draw @ canvas.

Here is my current code of locating mouse pointer inside the canvas:

$('#canvasID').mousedown(function(e) {   
    // Mouse down location
    var mouseX = e.pageX - this.offsetLeft;   
    var mouseY = e.pageY -
    this.offsetTop;
});

Of course my pages has a lot of includes, like I include header and menu box.

How can the mouse pointer be precise inside the canvas esp. from different resolution of pc?

Upvotes: 0

Views: 2117

Answers (2)

MSpreij
MSpreij

Reputation: 1152

Right, here we go: https://stackoverflow.com/a/4430498/126584
event.offsetX/Y are not supported in firefox >.<


Inside $('#canvasID').mousedown(function(e) { e.offsetX and e.offsetY should have the coordinates relative to the top-left corner of the canvas. For a quick and dirty way to see everything in e(vent), dump the contents in a <div id='debug'> with

$('#canvasID').mousedown(function(e) {
    debug(dump(e));
});

// debug (msg)
function debug (msg) {
    $('#debug').prepend(msg+'<br>\n');
}

// dump(ob)
function dump(ob) {
  var out;
  out = 'Properties:<br>\n';
  for (prop in ob) {
    out = out + prop + ': ' + ob[prop] + '<br>\n';
  }
  return out;
}

Long & late answer, just found this as I am playing with canvas right now :-) Hope it still helps someone.

Upvotes: 0

Teemu Ikonen
Teemu Ikonen

Reputation: 11929

This should return always right location on canvas.

$("#canvasID").mouseup(function(e) {
  var offset = $(this).offset();
  var mouseX = e.pageX - offset.left;
  var mouseY = e.pageY - offset.top;
});

Upvotes: 1

Related Questions