javascripthtmlcsscanvas

Canvas in basic HTML page always sized as 300x150


I have simplified my issue to a basic HTML document with a <canvas> element:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">

    <style>
      body {
        border: 1px solid #ff5500;
        background-color: black;
      }
      canvas {
        width: 100%;
        height: 100%;
      }
    </style>
</head>

<body>
 <canvas id="canv" style='width:1024px;height:768px'>
  </canvas>
</body>

</html>

But however I set the width and height (using pixels, percentages or viewport units), whether or not I set the style (e.g. style='width:1024px;height:768px'), and however I resize the browser window, the dev console always reports width x height as 300x150. Why is this, and how do I deal with it?

Here's the output from the dev console:

var c = document.getElementById("canv");
undefined
c.style.width
"1024px"
c.style.height
"768px"
c.width
300
c.height
150

The same behaviour occurs in both Chromium and Firefox.

I have trawled Stack Overflow and the web in general and found much on the difference between width and clientWidth, and a similar question regarding Fabric.js, but no answer to this specific question.


Solution

  • I think the width and height that you are referring to-- are html attributes and not css.

    They can be modified like this;

    <canvas width="1024" height="768" style="border:1px solid black;">
    </canvas>