-1

As the title says im trying to work with canvas but whenever i try to set its height and width to 100% height and width of the page it just overflows by a tiny bit. I have no clue why its happening and its very annoying when trying to make something.

Does anyone have a clue as to why it is happening?

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
    <title>Canvas Practice</title>
   <style type="text/css">
    canvas{
        height: 100%;
        width: 100%;
    }
    html,body
    {
        margin: 0;
        height: 100%;

    }
</style>
</head>
<body>
    <canvas></canvas>
    <script type="text/javascript" src="canvas.js"></script>
    </body>
</html>

This is my html with some basic inline css.

AquaProgramming
  • 115
  • 1
  • 1
  • 9

2 Answers2

0

The easiest thing to do is to always keep the canvas in its own div.

The only thing that will ever be in this div is the canvas.

Then you can use CSS to resize the div however you want. You want it as large as the body? Give the div width: 100%.

Then you can always rightfully do:

 canvas.width = theDiv.clientWidth;
canvas.height = theDiv.clientHeight;
Blesson Christy
  • 380
  • 3
  • 13
0

Add display: block; to your canvas and it will work. I have added background just for reference.

    canvas{
        height: 100%;
        width: 100%;
        display: block;
        background: #222;
    }
    html,body
    {
        margin: 0;
        height: 100%;

    }
<html lang="en">
<head>
   <meta charset="UTF-8">
    <title>Canvas Practice</title>
   
</head>
<body>
    <canvas></canvas>
    <script type="text/javascript" src="canvas.js"></script>
    </body>
</html>

Hope this help.

Rajan Benipuri
  • 1,772
  • 1
  • 9
  • 21