1

The following code works perfectly while the canvas is not fullscreen.

    let canvas = document.querySelector('canvas');
    let ctx = canvas.getContext('2d');

    document.addEventListener('mousemove',e=>{
        let br = canvas.getBoundingClientRect();
        let mouseX = e.clientX - br.left;
        let mouseY = e.clientY - br.top;
    });

However, after canvas.requestFullscreen() variables mouseX, mouseY do no longer represent the mouse's position on the canvas.
Is there any way to get the mouse's position relative to the canvas?

  • Does this answer your question? [JavaScript: incorrect mouse coords (pageX and pageY in fullscreen mode)](https://stackoverflow.com/questions/42132146/javascript-incorrect-mouse-coords-pagex-and-pagey-in-fullscreen-mode) – ggorlen May 27 '20 at 21:23

1 Answers1

2

After a long time I finally found a solution.

var FULLSCREEN = false;
document.onfullscreenchange = () => {FULLSCREEN = !FULLSCREEN};
// Keep Track of when Screen 

var mouseX=0,mouseY=0;

function map(v,n1,n2,m1,m2){
    return (v-n1)/(n2-n1)*(m2-m1)+m1;
}

doucment.addEventListener('mousedown',e=>{
        var x,y;
        var element = e.target;
        let br = element.getBoundingClientRect();
        if(FULLSCREEN){
            let ratio = window.innerHeight/canvas.height;
            let offset = (window.innerWidth-(canvas.width*ratio))/2;
            x = map(e.clientX-br.left-offset,0,canvas.width*ratio,0,element.width);
            y = map(e.clientY-br.top,0,canvas.height*ratio,0,element.height);
        } else {
            x = e.clientX - br.left;
            y = e.clientY - br.top;
        }
        mouseX = x;
        mouseY = y;
});

// Unfortunately this only works if the element is touching the top and bottom of the screen
// In other words, the ratio between the width and height of your screen must 
// be greater that the ratio of width to height for your element
  • I can't believe this is necessary, but I haven't been able to come up with anything less ridiculous for something as simple as "where on the canvas did the person click", so here we are... Thank you for chasing this down. – Mala Jul 11 '21 at 02:43
  • Thanks, this is exactly the problem I faced and this code works! That is, it works in Firefox but not in Chrome. I will try and see what is making it work differently between them (unless someone knows already....?) – PaulM Mar 07 '22 at 16:23