0

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?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
dyenair
  • 13
  • 6
  • You might want to take a look at this: http://dev.opera.com/articles/view/html5-canvas-painting/ – Emond Nov 24 '11 at 07:17
  • I didn't post this as an answer because there is no clear question. Could you explain (in the question) what problem you are having? – Emond Nov 24 '11 at 07:27
  • Sir thank you. I already solved the problem. Thank you anyways. – dyenair Nov 24 '11 at 08:08

2 Answers2

1

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;
});
Teemu Ikonen
  • 11,861
  • 4
  • 22
  • 35
0

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.

Community
  • 1
  • 1
MSpreij
  • 1,142
  • 13
  • 20