[英]How can I get the mouse position on an HTML5 canvas when canvas is fullscreen?
当 canvas 不是全屏时,以下代码可以完美运行。
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;
});
但是,在canvas.requestFullscreen()
变量mouseX, mouseY
不再代表 canvas 上的鼠标 position。
相对于canvas,有什么办法可以得到鼠标的position?
找了好久终于找到了解决办法。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.