Canvas in basic HTML page always sized as 300x150.

Viewed 1863

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.

2 Answers

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>

You have to change canv.width or .height in JS or set the attribute in HTML directly. Without any CSS or JS needed.

Example:

var can = document.querySelector("#testC");
var can2 = document.querySelector("#testC2");

console.log("Canvas before JS: ", can.width, "x", can.height);
console.log("Canvas in HMTL: ", can2.width, "x", can2.height);

can.width = 600;
can.height = 600;

console.log("Canvas after JS: ", can.width, "x", can.height);
console.log("Canvas in HMTL: ", can2.width, "x", can2.height);
<canvas id="testC" width="300" height="300">
<canvas id="testC2" width="600" height="600">

This will log:

Canvas before JS: 300x300
Canvas in HMTL: 600x600
Canvas after JS: 600x600
Canvas in HMTL: 600x600
Related