html 计算动态大小的浏览器窗口内的可见空间

kpbwa7wx  于 2023-04-18  发布在  其他
关注(0)|答案(1)|浏览(92)

我已经开始了一个小项目,并决定在网页中创建一个视频游戏(一个简单的Snap游戏),但我在使用动态大小的窗口时遇到了一点障碍。到目前为止,我已经设置了网页,并决定在画布元素中构建游戏,利用javascript进行管道,实体和环境绘制等。
我希望游戏窗口(canvas元素)保持给定的长宽比(在本例中:到目前为止,我已经成功地使用canvas.style.width = "100%"window.innerWidth更改宽度以匹配窗口宽度,但高度是一个问题。一旦窗口达到一定的宽度,它就变得太高而不能在页面上一次全部呈现。
总结如下:如何计算窗口的高度,使画布不会超过可见窗口的底部,从而导致画布过大,需要滚动条?
到目前为止的代码:index.html

<html lang="zxx">

<head>
    <meta charset="utf-8">
    <title> Pairs </title>
    <link rel="stylesheet" type="text/css" href="Style.css">
</head>

<body>
    <h1> Pairs </h1>
    <hr>
    <div class="GameDiv" id="gameDiv">
        <canvas>Sorry, your browser dosen't support HTML Canvas.</canvas>
    </div>
</body>

<script src="game.js"></script>
</html>

game.js:

// Canvas set-up
const canvas = document.querySelector("canvas");
const canvasDims = { width: 300, height: 185 };
const gameDiv = document.getElementById("gameDiv");
const ctx = canvas.getContext("2d");

// dynamic screen fit
function resizeCanvas() {
    let dims = {
        width: window.innerWidth,
        height: (canvasDims.height / canvasDims.width) * window.innerWidth
    };

    canvas.style.aspectRatio = canvasDims.width / canvasDims.height;

    if (window.innerHeight > dims.height) {
        canvas.style.width = "100%";
        canvas.style.height = "initial";
        canvas.style.top = `calc(50% - ${dims.height + "px"}/2)`;
    } else {
        // where the problems begin
        canvas.style.height = screen.height;
        canvas.style.width = screen.height + (screen.height/canvas.style.aspectRatio);
        canvas.style.top = "initial";
    }
    
}

window.addEventListener("resize", resizeCanvas);
resizeCanvas();
mhd8tkvw

mhd8tkvw1#

我已经设法找到了一个解决方案。它需要对函数进行一些修改,但它在实践中确实有效,我不确定我所做的任何事情是否是最佳实践,但是,它现在符合我的目的。如果有人看到这一点,并对更好的实践有任何意见,请告诉我,我对JS和Web开发总体来说还是相当陌生的。
更新代码:

// dynamic screen fit
function resizeCanvas() {
    let dims = {
        width: window.innerWidth,
        height: (canvasDims.height / canvasDims.width) * window.innerWidth
    };

    var aspectRatio = canvasDims.width / canvasDims.height;
    canvas.style.aspectRatio = aspectRatio;

    var distToTop = window.pageYOffset + canvas.getBoundingClientRect().top;
    var vh = window.innerHeight/100;
    var vw = window.innerWidth/100;
    var height = window.innerHeight - (distToTop + vh)

    if (height > dims.height) {
        canvas.style.width = dims.width - 2*vw + "px";
        canvas.style.height = dims.height + "px";
    } else {
        var width = height * aspectRatio + "px"
        canvas.style.height = height +"px";
        canvas.style.width = width;
    }
}

相关问题