Saturday, May 11, 2013

How to get coordinates of a mouse click on a canvas element

I have a problem with canvas and handling clicks. It looks that there is no easy way to get a relative coordinate of click inside a given DOM Element. After Googling a little, I've choosen the below solution:

The findRealOffset should be called everytime a position of canvas or layout of website changes.

var totalOffsetX = 0;
var totalOffsetY = 0;

findRealOffset() {
  var canvasX = 0;
  var canvasY = 0;
  var currentElement = canvas;
  while (currentElement != null) {
    totalOffsetX += currentElement.offsetLeft;
    totalOffsetY += currentElement.offsetTop;
    currentElement = currentElement.offsetParent;
  }
}

relativeCoord(e) {
  var canvasX = e.pageX - totalOffsetX;
  var canvasY = e.pageY - totalOffsetY;

  // Fix for variable canvas width
  canvasX = ( canvasX * (canvas.width / canvas.offsetWidth) ).round();
  canvasY = ( canvasY * (canvas.height / canvas.offsetHeight) ).round();
  return {'x':canvasX, 'y':canvasY};
}

Source: http://stackoverflow.com/questions/55677/how-do-i-get-the-coordinates-of-a-mouse-click-on-a-canvas-element