Search code examples
javascriptcanvascoordinatespixel

Canvas pixel coordinate offset after scroll bar is used


I'm using a canvas at the top of a page. Im writing out the pixel coordinates from the canvas at a mousemove event. Normally, the most bottom Y-value is equal to the canvas height, i e. 700px. But after scrollbar is used to scroll down a bit on the page, the bottom y-coordinate in the canvas will change accordingly to say 400px instead.

            document.getElementById("mapcanvas").addEventListener("mousemove", getPosition, false);

            function getPosition(event)
            {
              var x = event.x;
              var y = event.y;

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

              x -= canvas.offsetLeft;
              y -= canvas.offsetTop;



             document.getElementById("canvascoords").innerHTML = "Canvascoords: "+ "x=" + x + ", y=" + y;





            }

... Where "mapcanvas" is my div holding the canvas.

Any ideas of making the y-coordinate independent from usage of scroll bar so that the lower y-coordinate always i 700px?


Solution

  • As you've discovered, canvas.offsetLeft & canvas.offsetTop do not account for scrolling.

    To account for scrolling, you can use canvas.getBoundingClientRect

    var BB=canvas.getBoundingClientRect();
    
    var x=event.clientX-BB.left;
    var y=event.clientY-BB.top;
    

    BTW, you might want to fetch a reference to the canvas element just once outside your getPosition() function instead of fetching it repeatedly inside getPosition().

    var canvas = document.getElementById("mapcanvas");
    
    function getPosition(event){
    
    ...