skip to Main Content

Basically I created a canvas with html and from the css I gave it a ratio of 16/9 and I put a width of 100ww, I also put a border, but the problem is that my canvas is bigger than what I see on the screen.

#canvas{
width: 100vw;
aspect-ratio: 16/9;
border: 5px solid red;

}

I had to reduce the size and padding to compensate.


*{

margin: 5px;

margin-left: 3%

}

.canvas{

width: 80vw;

aspect-ratio: 16/9

border: 3px solid red;

}

This works but I was expecting a full screen if you can say so

Screenshots:

html

enter image description here

enter image description here

2

Answers


  1. You have to subtract the border from the width of your canvas, like this:

    body {
      margin: 0;
      overflow: hidden;
    }
    
    #canvas{
      width: calc(100vw - 10px);
      aspect-ratio: 16/9;
      border: 5px solid red;
    
    }
    

    See: https://codepen.io/kikosoft/pen/ZEmjRxW

    Note that I set the margin of the body to zero. If you have a non-zero margin you also have to subtract that.

    Login or Signup to reply.
  2. For a dynamic solution to canvas size try this in your JS:

    const canvas=document.querySelector("canvas")
    canvas.width=window.innerWidth-canvas.offsetLeft
    canvas.height=window.innerHeight-canvas.offsetTop
    

    It’ll set the canvas to the size of your window as well as compensate for any other elements in your HTML.
    Also, add an event listener to reset the canvas size when you resize the window like below:

    addEventListener("resize",function(){
        canvas.width=innerWidth
        canvas.height=innerHeight
        //INSERT FUNCTIONS TO CALL HERE!!
    })
    

    You’ll need to call any functions that need resetting like ones that generate objects.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search