使画布尽可能大,没有滚动条

Make canvas as big as possible without scrollbars

本文关键字:滚动条 尽可能      更新时间:2023-09-26

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

将画布的宽度和高度设置为$(window).height()和$(window).width()会产生滚动条。减少几个像素的宽度是不可靠的,因为我需要减少的数字是不同的,这取决于浏览器。

是否有跨浏览器的方式来做到这一点?

在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>

update:你可能还想给页面附加一个调整大小的监听器,这样如果用户调整页面的大小,你可以重置宽度/高度

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

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