0

I'm sort of new to javascript and Ive been looking up documentElement, clientWidth & clientHeight and trying to figure out why its setting my canvas to the size of 300px by 150px. Maybe I'm not understanding something on how it's getting those dimensions. Can someone help explain?

Here is my current code

<canvas id="canvas"></canvas>

<script>
var canvas = document.getElementByID('canvas');
var ctx = canvas.getContext('2d');

canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
</script>

3 Answers3

1

The issue is a typo in the code, so the code never runs.

change

var canvas = document.getElementByID('canvas');

to

var canvas = document.getElementById('canvas');

notice the lowercase d

adeneo
  • 312,895
  • 29
  • 395
  • 388
1

The "height" and "width" properties of the canvas object control the size of the canvas coordinate system, not the size of the element on the screen. If you don't impose some CSS rules for that, you get the default on-screen size.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Ha ha @adeneo it looks like we both had the same reaction on opposite sides of the answer :) – Pointy Jun 25 '14 at 17:26
  • Well, mine wasn't quite accurate, I knew it was getting the default size, but thought it was because `documentElement` isn't something you generally use for anything, and I didn't think it had size, but testing it it seems like it does, and then I noticed your answer, it is of course getting the default size because setting the attributes/properties on the element doesn't do the same thing as setting the styles, it's the "classical canvas size" issue. – adeneo Jun 25 '14 at 17:30
  • Well I don't know if I'm right about this; or at least not completely right. Setting the "width" and "height" seems to work fine in Firefox. – Pointy Jun 25 '14 at 17:32
  • I think we're both thinking too complicated, I updated my answer ? – adeneo Jun 25 '14 at 17:35
  • @adeneo ha ha yes I bet that's it! – Pointy Jun 25 '14 at 17:36
  • It is true, OP, that the on-screen size and the coordinate space are independent. You can have a canvas that's 2000x3000 and show it in a 20px by 30px screen area. – Pointy Jun 25 '14 at 17:37
  • At least it seem to work in a fiddle when fixing the typo, I didn't even notice it. And yes, you're right as well, setting the height and width styles and the height and width attributes/properties do completely different things, which is really confusing sometimes. – adeneo Jun 25 '14 at 17:39
  • 1
    And I would never use `documentElement`, using just the document or window would be a much better option. – adeneo Jun 25 '14 at 17:39
1

Looks like its a default canvas size issue. See this post with a similiar issue. I assume you're in Chrome? canvas default size

Community
  • 1
  • 1
Nimrod5000
  • 130
  • 8