Why do i have set my canvas width to window innerWidth in JS and canvas width 100% in css?

Viewed 54

I don't get why I can't set the width and height to 100% in CSS OR set width and height to inner window width and height but, I have to do both. If I don't set both of them my canvas element won't show my drawing. Same thing with height too. Here's my code:

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>TESTING CANVAS DRAWING</title>
    <style>
      body {
        margin: 0px;
      }

      canvas {
        border: 2px soild black;
        width: 100%;
        height: 100%;
      }
    </style>
  </head>
  <body>
    <canvas>
      Your browser does not support the HTML5 canvas tag.
    </canvas>
    <script>
      //startup code
      let canvas = document.getElementsByTagName("canvas")[0];
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight

      //drawing

      let context = canvas.getContext("2d");
      context.fillRect(659, 327, 100, 100); // pixel coordinates start from the the top right
    </script>
  </body>
</html>
1 Answers
Related