【问题标题】:How to correctly get mouse co ordinates in resizable canvas?如何在可调整大小的画布中正确获取鼠标坐标?
【发布时间】:2016-06-07 15:09:10
【问题描述】:

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

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 {
        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;

【问题讨论】:

  • 请在var scaleToFitX = gameWidth / width; 行中定义width 的问题中澄清height 有类似的问题。请注意代码笔中的所有警报使其难以查看(计算机总是获胜)
  • 我已经编辑了问题并更改了代码笔链接。现在您可以不间断地阅读它了。

标签: javascript css html canvas pong


【解决方案1】:

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

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 文件,因为您正在转换您不确定的东西。

【讨论】:

  • 好的,我试着按照你说的去做。我在 mousemove 事件中将 scaleToFitX 乘以 mouseY,但仍然没有效果。我做错了吗?
  • 您是否删除了 css 转换?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-22
  • 2017-05-28
  • 2022-08-18
  • 1970-01-01
  • 2020-02-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多