0

There are plenty of discussions on Stackoverflow, on how to get the mouse coordinates in a Canvas. I finally found, that the solution outlined in https://stackoverflow.com/a/5417934 works well for me, WITH ONE EXCEPTION:

If I put a style definition for the canvas border into my document, i.e.

<style>
  canvas { border: 42px solid red; }
</style>

The mouse position I get is off by exactly the border size (I can easily verify this by playing around with the border size). As a temporary solution, I manually adjusted the mouse coordinates by the border size, ending up with the following function for getting the mouse coordinates:

function getCursorPosition1(event) { 
  var canoffset=$('#pinaka').offset(); // Id of canvas is 'pinaka'
  var x=event.clientX+document.body.scrollLeft+document.documentElement.scrollLeft-Math.floor(canoffset.left) - 42;
  var y=event.clientY + document.body.scrollTop + document.documentElement.scrollTop - Math.floor(canoffset.top) + 1 - 42;
  return [x,y]
}

Of course this is ugly. Is there a way to automatically derive the border size in my code?

Community
  • 1
  • 1
user1934428
  • 19,864
  • 7
  • 42
  • 87
  • 1
    using getClientBoundingRect is the way to go : http://stackoverflow.com/questions/20060691/most-modern-method-of-getting-mouse-position-within-a-canvas-in-native-javascrip/20061533#20061533 – GameAlchemist Dec 12 '13 at 11:32

2 Answers2

2

You can get the border width using window.getComputedStyle.

<canvas id="canvas"></canvas>

var canvas = document.getElementById("canvas");
var computedStyle = window.getComputedStyle(canvas,null);
var topBorder=computedStyle.getPropertyValue("border-top-width");
var leftBorder=computedStyle.getPropertyValue("border-left-width");
var bottomBorder=computedStyle.getPropertyValue("border-bottom-width");
var rightBorder=computedStyle.getPropertyValue("border-right-width");

(requires IE9+)

markE
  • 102,905
  • 11
  • 164
  • 176
0

Thank you a lot; combining the answer and comment I received on my question, I ended up with the following solution:

var can=document.getElementById("pinaka");
function getCursorPosition(event) {
var computedStyle = window.getComputedStyle(can,null);
var topBorder=parseInt(computedStyle.getPropertyValue("border-top-width"),10);
var leftBorder=parseInt(computedStyle.getPropertyValue("border-left-width"),10);
var rect=can.getBoundingClientRect();
var x=event.clientX - rect.left - leftBorder;
var y=event.clientY - rect.top - topBorder;
return [x,y]
}

It seems to provide the correct value for the (few) cases I tried.

user1934428
  • 19,864
  • 7
  • 42
  • 87