0

here are my 2 files

HTML:

<html>

  <head>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
    <canvas id=myCanvas></canvas>

    <script>
      var c=document.getElementById("myCanvas");
      alert(c.width)
    </script>

  </body>

</html>

CSS:

canvas {
  width:480;
  height:360;
  position:absolute;
  background-color:grey;
}

Clearly, the width of my canvas element would be 480, but for some reason, alert(c.width) returns 300.

2 Answers2

2

It's happening because c.width refers to the element's width attribute. If that attribute is not present in the canvas element, you'll get the default value for it, which is 300px. The same would happen for height (150px).

To get the real canvas width, you can use getBoundingClientRect(). Also, don't forget to add 'px' after your CSS numeric values for width and height.

canvas {
  width: 480px;
  height: 360px;
  position:absolute;
  background-color:grey;
}
<html>

  <head>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
    <canvas id=myCanvas></canvas>

    <script>
      var c = document.getElementById("myCanvas");
      alert(c.getBoundingClientRect().width)
    </script>

  </body>

</html>
  • While this does return 480 like expected, I am still having an issue where draw methods still think the canvas is 300x150, with the canvas rendering stretched to 480x360. Would there be any way to fix this problem too? – TetraPengwin Aug 09 '21 at 02:45
  • 1
    In this case, you must use the width and height attributes. That's because "`width` and `height` attributes determine the width or height of the canvas's coordinate system, whereas the CSS properties just determine the size of the box in which it will be shown", as from SamB's answer in this question: https://stackoverflow.com/questions/2588181/canvas-is-stretched-when-using-css-but-normal-with-width-height-properties. –  Aug 09 '21 at 02:52
-1

Try using c.offsetWidth instead of c.width. As @BrunoSdoukos has already mentioned width in the context of how you are trying to use it requires that you set the width as an attribute on the <canvas> element, like this:

<canvas id="myCanvas" width="480"></canvas>

Because there isn't a width attribute set on the HTML element itself, using c.width will return the default width, which is 300px.

Because you have specified the element's width using CSS in order to get the elements width in this case you should use:

c.offsetWidth

Here is what MDN says about HTMLElement.offsetWidth:

Typically, offsetWidth is a measurement in pixels of the element's CSS width, including any borders, padding, and vertical scrollbars (if rendered). It does not include the width of pseudo-elements such as ::before or ::after.

You can ready more about this property here:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth