当 canvas 全屏时,如何获取 HTML5 canvas 上的鼠标位置?
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 上的位置。
有什么方法可以获取鼠标相对于 canvas?
的位置
找了半天终于找到解决方法了
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
以下代码在 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 上的位置。
有什么方法可以获取鼠标相对于 canvas?
找了半天终于找到解决方法了
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