Search code examples
javascripthtmlcanvasmouseentermouseclick-event

How can I test mouse detection on canvas (JavaScript) when the canvas's height exceeds the screen's height (when the scroll bar appears)


I can test mouse coordinates on canvas when there is no scroll bar with:

var mx = evt.clientX - canvas.offsetX
var my = evt.clientY - canvas.offsetY

However, when I scroll down the webpage, and I reposition the mouse the coordinates are skewed.

Any suggestions?


Solution

  • It sounds like you are trying to test the mouse's position on the canvas (and not the mouse's position on the screen). For that, evt.offsetX and evt.offsetY are sufficient even when there is a scrollbar.

    Please see the working live demo here, and open your JS console and you will be able to see the cursor's coordinates relative to the canvas:

    var canvas = document.getElementsByTagName("canvas")[0];
    
    canvas.onmousemove = function(evt) {
        var mx = evt.offsetX;
        var my = evt.offsetY;
        console.log(mx, my);
    }
    <canvas height="800" width="200" style="border: solid black 1px"></canvas>