Sir
Sir

Reputation: 8280

Mouse position in canvas without a library?

I been searching around to find how to get the mouse position relative to canvas but without a JS library...can't see to find any examples except for jquery!

I use this to start my function:

 canvas = document.getElementById("canvas");  
 ctx = canvas.getContext("2d"); 
 canvas.addEventListener("mousedown", mousePos, false);

But e.pageX and e.pageY is affected by the position of the canvas. I need to remove that issue so the maths is correct so its only based on the canvas.

Can this be done without a JS library? As I have only ever seen it done with jquery which i'm trying to avoid as much as possible.

Upvotes: 0

Views: 979

Answers (3)

Jeffrey Sweeney
Jeffrey Sweeney

Reputation: 6124

First you need to get the offset of the canvas element, or how far right + down it is from the top-left corner.

When the mouse moves, factor in the offset variables to the mouse's position.

This code should do the trick:

var canvas = document.getElementById("canvas");


var xOff=0, yOff=0;



for(var obj = canvas; obj != null; obj = obj.offsetParent) {
    xOff += obj.scrollLeft - obj.offsetLeft;
    yOff += obj.scrollTop - obj.offsetTop;
}



canvas.addEventListener("mousemove", function(e) {

                        var x = e.x + xOff;
                        var y = e.y + yOff;


                        var ctx = canvas.getContext('2d');
                        ctx.clearRect(0, 0, 100, 100);
                        ctx.fillText(x + " - " + y, 40, 40);  

                        }, true);

Upvotes: 1

ChristopheCVB
ChristopheCVB

Reputation: 7315

I'm using :

var x;
var y;
if (e.pageX || e.pageY)
{
    x = e.pageX;
    y = e.pageY;
}
else {
    x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
    y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
} 
x -= gCanvasElement.offsetLeft;
y -= gCanvasElement.offsetTop;

Upvotes: 1

epascarello
epascarello

Reputation: 207521

var findPos = function(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) { 
        do {
           curleft += obj.offsetLeft;
           curtop += obj.offsetTop; 
        } while (obj = obj.offsetParent);
    }
    return { x : curleft, y : curtop };
};

Get the position of the canvas element and subtract the x and y from it.

Upvotes: 1

Related Questions