Search code examples
javascriptcsshtml5-canvas

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


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>

Solution

  • CSS and javascript, in this case, are referring to two separate sizes. The Canvas element has it's own specific dimensions (default 300x150 i think) as well as the HTMLElement dimensions that can be controlled with CSS. You can just set the dimensions in css and use relative values, eg:

          //startup code
          let canvas = document.getElementsByTagName("canvas")[0];
          //canvas.width = window.innerWidth;
          //canvas.height = window.innerHeight
    
          //drawing
          let x = 659 * canvas.width/ document.body.offsetWidth;
          let width = 100 * canvas.width / document.body.offsetWidth;
          let y = 327 * canvas.height / document.body.offsetHeight;
          let height = 100 * canvas.height / document.body.offsetHeight;
          let context = canvas.getContext("2d");
          context.fillRect(x, y, width, height); // pixel coordinates start from the the top right
    

    I'm not setting the values but it should look the same if a little blurrier. Think of it as a monitor; the CSS controls the physical size of the monitor and JS canvas dimensions are the resolution.