Kaninepete
Kaninepete

Reputation: 1447

Mouse coordinates on Canvas without Jquery

I am currently using:

e.pageX - $("#canvas").offset().left

This is the only thing I am using Jquery for, so I would prefer to re-write this using just javascript.

What can I use to replace this?

Upvotes: 0

Views: 2393

Answers (3)

user1083202
user1083202

Reputation: 3182

You can replace it by the below code

<canvas onmouseDown="mouseDown(event)" width="500" height="500"></canvas>


function mouseDown(e)
{
  var x=e.clientX-canvas.offsetLeft;
  var y=e.clientY-canvas.offsetTop; 
}

Upvotes: 0

N Rohler
N Rohler

Reputation: 4615

var x = e.offsetX,
    y = e.offsetY;

Updated (again) for (correct) Firefox compatibility:

var rect = e.target.getBoundingClientRect();
var x = e.offsetX || e.pageX - rect.left - window.scrollX,
    y = e.offsetY || e.pageY - rect.top - window.scrollY;

Upvotes: 1

MaxArt
MaxArt

Reputation: 22627

The answer provided by N Rohler works well only in Internet Explorer (with some bugs prior to IE8 - but I guess it won't be a problem for you since you're using a canvas and pageX), and in Opera if the padding is 0, and in Safari/Chrome if the border width is 0 too. In Firefox, unfortunately, offsetX and offsetY are undefined. http://www.quirksmode.org/dom/w3c_cssom.html#mousepos

Kaninepete, I think you should reconsider, for the sake of simplicity, the way of getting the mouse coordinates relatively to your canvas element. All you have to do is to calculate the position of the canvas, which is a pretty simple task using .getBoundingClientRect() (also, don't forget to add scroll offsets if necessary), and subtract it from pageX and pageY.

Upvotes: 2

Related Questions