Javascript 使画布尽可能大,无需滚动条

Javascript 使画布尽可能大,无需滚动条,javascript,jquery,html5-canvas,Javascript,Jquery,Html5 Canvas,我想创建一个网页,其中包含一个画布对象,该对象填充屏幕而不创建滚动条 将画布宽度和高度设置为$(window).height()和$(window).width()将生成滚动条。将宽度减少几个像素是不可靠的,因为我需要减少的数量因浏览器而异 有没有跨浏览器的方法可以做到这一点?所有支持canvas元素的浏览器都支持css固定定位。所以你可以这样做: #my_canvas { position:fixed; top:0; left:0; bottom:0; right:0; }

我想创建一个网页,其中包含一个画布对象,该对象填充屏幕而不创建滚动条

将画布宽度和高度设置为$(window).height()和$(window).width()将生成滚动条。将宽度减少几个像素是不可靠的,因为我需要减少的数量因浏览器而异


有没有跨浏览器的方法可以做到这一点?

所有支持canvas元素的浏览器都支持css固定定位。所以你可以这样做:

#my_canvas {
  position:fixed;
  top:0;
  left:0;
  bottom:0;
  right:0;
}

在Chrome中,这适用于我

<html>
    <head>
        <title></title>
        <script>
           function init() {
                var canvasBG = document.getElementById("test");
                var ctxBG = canvasBG.getContext("2d");

                canvasBG.style.width = window.innerWidth;
                canvasBG.style.height = window.innerHeight;
            };

            window.onload = init;
        </script>
    </head>
    <body>
        <canvas id="test" style="background:#eeeeee; 
               margin:0; padding:0; 
               position:absolute; 
               top:0; left:0">
        </canvas>
    </body>
    </html>

函数init(){
var canvasBG=document.getElementById(“测试”);
var ctxBG=canvasBG.getContext(“2d”);
canvasBG.style.width=window.innerWidth;
canvasBG.style.height=window.innerHeight;
};
window.onload=init;

更新:您可能还希望在页面上附加一个调整大小的侦听器,以便如果用户调整页面大小,您可以重置宽度/高度。

根据我的经验,这会拉伸画布内容,而不是更改绘图区域。这只会使画布保持相同的大小–甚至不会拉伸,至少在Chrome中不会。您可以使用position:fixed而不是position:absolute,就像在接受的答案中一样,但是结果是一样的–您仍然需要提供高度和宽度。您在“\u canvasBG”中有一个随机下划线,这打破了您的示例。否则,它在2020年仍然有效;)谢谢@user1596274。固定的。