Search code examples
javascripthtmlhtml5-canvasfullscreenresolution

Canvas in HTML to fit monitor screen with Javascript not working as I still see scrollbars for X and Y


I'm trying to create a program with HMTL, just to create a canvas and draw in the canvas with Javascript. I need the program to run in a computer and in the tablet, so i want the canvas to adjust to the side of the monitor. I thought it would be just setting width and height of canvas to screen.width and screen.height, but in Chrome the canvas is bigger than the screen and I have the scrollbars to see the rest of the window with the canvas. What am I doing wrong?

<body>
        <div id="main_div">
        <canvas id="myCanvas" style="border:1px solid #000000;">
        <script>
    var canvas = document.getElementsByTagName('canvas')[0];
    canvas.width  = screen.width;
    canvas.height = screen.height;
    </script>
    </canvas>
    </div>
      </body>

Solution

  • Unless the user is in fullscreen mode, the screen size is larger than the window size even if there is only one window on the screen (because there is space left for the browser's search bars and so on). You probably want to find the dimensions of the window rather than the physical screen so you can replace

    canvas.width  = screen.width;
    canvas.height = screen.height;
    

    with

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    

    This will deal with different sizes of window, though to be responsive you could consider using 100vw and 100vh instead - but in this case be aware that on some mobile systems vw and vh are fixed (don't change if the user scrolls so some of the browser bars disappear) so you can lose the bottom of your window until the user scrolls up.