skip to Main Content

I am new to HTML and JS and am trying to code a basic game. However, I keep running into the issue that scroll bars appear, meaning that something is bigger than it should be. I looked into it a bit, and it seems it is the html tag which is too high for the window. I need to know how to fix this.

This is the code I’m using to make it take the whole window (these are the first 3 lines of code):

let canvas = document.getElementById("mainCanvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

3

Answers


  1. Chosen as BEST ANSWER

    I just found out I can put overflow: hidden; in the CSS which fixes my problem.


  2. If you want your canvas to take up whole space, you could just add this to your canvas properties.

    let canvas = document.getElementById("mainCanvas");
    canvas.width = "100vw";
    canvas.height = "100vh";
    

    or

    let canvas = document.getElementById("mainCanvas");
    canvas.width = "100vw";
    canvas.height = "100%";
    

    The vh stands for viewport height and
    vw for viewport width.

    What it does is basically occupy the height and width of your viewport in the browser. I hope it helps you 😉

    Login or Signup to reply.
    1. Make sure your html and body are not adding any margin or padding:

    css

    html, body {
        margin: 0;
        padding: 0;
    }
    
    1. Use css to set your mainCanvas element to viewport extents and suggested in Aditya’s answer:

    css

    #mainCanvas {
        height: 100vh;
        width: 100vw;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search