【发布时间】: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