我有一个可以缩放到 16:9
纵横比的 Canvas 。但是,鼠标不考虑偏移量(黑色背景)。
绿色虚线标记 Canvas 。在边缘,鼠标应显示:Mouse : 0% | 23%
而不是 鼠标:7% | 23%
。
问题好像出在这里:
var x = Math.floor( mouse.x / canvas.width * 100 );
var y = Math.floor( mouse.y / canvas.height * 100 );
当我进入全屏模式时它工作正常。 (因为没有偏移量) 但除此之外它不会考虑偏移量。
附加代码:
CSS:
#aspectoverlay {
/* 16:9 */
width: 100vw;
height: 56.25vw; /* 100/56.25 = 1.778 */
border: 1px #AFFF00 dashed;
max-height: 100vh;
max-width: 177.78vh; /* 16/9 = 1.778 */
margin: auto;
position: absolute;
top:0;bottom:0; /* vertical center */
left:0;right:0; /* horizontal center */
z-index: 100;
opacity: 1;
}
JS:
var canvas = document.getElementById('aspectoverlay');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext('2d');
window.addEventListener('resize', resizeCanvas, false);
function resizeCanvas () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
canvas.addEventListener('mousemove', function(e){
mouse.x = e.x;
mouse.y = e.y;
});
var x = Math.floor( mouse.x / canvas.width * 100 );
var y = Math.floor( mouse.y / canvas.height * 100 );
ctx.fillText("Mouse : " + x + "% | " + y + "%", 50,50);
最佳答案
你只需要像这样考虑元素的偏移
mouse.x = e.x - this.offsetLeft;
mouse.y = e.y - this.offsetTop;
并且由于您正在使用 CSS 调整 Canvas 大小并将 Canvas 设置为 innerHeight 和 Width,因此您不能再使用 Canvas width
和 height
进行计算使用 offsetWidth
和 offsetHeight
var x = Math.floor(mouse.x / canvas.offsetWidth * 100);
var y = Math.floor(mouse.y / canvas.offsetHeight * 100);
var canvas = document.getElementById('aspectoverlay');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext('2d'),
mouse = {
x: 0,
y: 0
};
ctx.fillStyle = "#fff";
window.addEventListener('resize', resizeCanvas, false);
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.fillStyle = "#fff";
}
canvas.addEventListener('mousemove', function (e) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
mouse.x = e.x - this.offsetLeft;
mouse.y = e.y - this.offsetTop;
var x = Math.floor(mouse.x / canvas.offsetWidth * 100);
var y = Math.floor(mouse.y / canvas.offsetHeight * 100);
ctx.fillText("Mouse : " + x + "% | " + y + "%", 50, 50);
});
关于javascript - 使用 CSS 宽高比时更正元素上的鼠标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24461369/