javascript - 使用 CSS 宽高比时更正元素上的鼠标位置

标签 javascript css canvas mouse aspect-ratio

我有一个可以缩放到 16:9 纵横比的 Canvas 。但是,鼠标不考虑偏移量(黑色背景)。

绿色虚线标记 Canvas 。在边缘,鼠标应显示:Mouse : 0% | 23% 而不是 鼠标:7% | 23%

enter image description here

问题好像出在这里:

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 widthheight 进行计算使用 offsetWidthoffsetHeight

var x = Math.floor(mouse.x / canvas.offsetWidth * 100);
var y = Math.floor(mouse.y / canvas.offsetHeight * 100);

Live Demo

Full Screen

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/

相关文章:

javascript - 如何在 google 和 API 的操作中使用 async 和 wait

javascript - 电子查找器问题。尝试复制文件时未定义不是函数错误

javascript - 为什么在循环访问数组中的 JSON 对象时会出现语法错误?如何正确提取 JSON?

javascript - 如何从另一个矩形中驱逐一个矩形 - Javascript

javascript - p5.j​​s 中的噪声梯度

javascript - 基于下拉列表在 Canvas 上进行缓动的动画圆圈

html - XSL 中的表列拆分问题

html - 尽管上部 div 有其他边框,但下部 div 边框可见

css - 下拉菜单中的顶级菜单项

javascript - 如何在 HTML5 Canvas 中临时更改圆圈颜色