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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.