当 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
关于javascript - 当 Canvas 全屏时,如何获取 HTML5 Canvas 上的鼠标位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62049700/