Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Solution 2:

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;

Solution 3:

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);

Post a Comment for "Mouse Position In Canvas Without A Library?"