javascript - 如何在可调整大小的 Canvas 中正确获取鼠标坐标?

标签 javascript css html canvas pong

我使用 canvas 元素在 JavaScript 中创建了一个 Pong 游戏。为了增加我的知识,我还附加了一个调整 Canvas 大小的函数,如下所示:

window.addEventListener("resize", OnResizeCalled, false); 

function OnResizeCalled() { 
    canvas.style.width = window.innerWidth + 'px'; 
    canvas.style.height = window.innerHeight + 'px'

    var gameWidth = window.innerWidth; 
    var gameHeight = window.innerHeight; 
    var scaleToFitX = gameWidth / width; 
    var scaleToFitY = gameHeight / height; 

    var currentScreenRatio = gameWidth / gameHeight; 
    var optimalRatio = Math.min(scaleToFitX, scaleToFitY); 

    if (currentScreenRatio >= 1.77 && currentScreenRatio <= 1.79) { 
        canvas.style.width = gameWidth + "px"; 
        canvas.style.height = gameHeight + "px"; 
    } 
    else { 
        canvas.style.width = width * optimalRatio + "px"; 
        canvas.style.height = height * optimalRatio + "px"; 
    } 
}

然后我将 Canvas 居中,如下所示:

canvas {
        position: absolute;
        top: 0px;
        left: 0px;
        transform: translate(-50%, -50%);*/
}

当我通过调整浏览器大小来玩游戏时,游戏也正确调整了大小,但桨的移动不准确。鼠标定位不正确。

我对鼠标移动进行了编码,如下所示:

function playerBatMove(event) {
        mouseY = event.clientY - canvas.offsetTop;
        if (mouseY <= 19) {mouseY = 20};
        if (mouseY+playerBat.batHeight >= height-19) {mouseY = (height-20)-playerBat.batHeight};
        playerBat.y = mouseY; 
};

除了鼠标问题之外,其他一切都很好......甚至图形比例也完美。

我获取鼠标坐标的方式是否有问题,或者我的调整大小功能有一些错误?如有任何帮助,我们将不胜感激。

谢谢。您可以在这里找到完整的代码 Pong game on CodePen

编辑:我在代码开头声明了变量宽度和高度。

var height = 500;
var width = 700;

最佳答案

我将编辑评论以便您更容易理解

function playerBatMove(event) {
    mouseY = event.clientY* (newHeight/oldHeight) - canvas.offsetTop;
     //the scale factor is newHeight/oldHeight, or how much you multiplied
     // or you can just say 1/scaleY

    playerBat.y = mouseY; 
};

你在这里所说的是你想要获取鼠标事件。然而,仅将其视为未缩放。 canvas.offsetTop 出现较晚的原因是 offsetTop 根本没有缩放

还请记住:删除你的 css 文件,确保它有效,然后添加你的 css 文件,因为你正在转换你的东西,但我不太确定。

关于javascript - 如何在可调整大小的 Canvas 中正确获取鼠标坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37640781/

相关文章:

css - 将div放在图像之间

css - 使用 css 变换移动时,SVG 图像变得模糊和闪烁

html - CSS 背景样式在设置部分中的元素样式时不起作用

javascript - 如何在innerHTML中添加调用电话号码链接

javascript - 一次调用数组中的多个元素?

对象内的javascript空数组

javascript - 按下按钮时从数组中返回随机字符串

javascript - 不输入指令

html - 使用 CSS 将 Img Src 更改为父级 A href

php - 使用 php 电子邮件生成带有动态值的 html