我使用 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/