1

I have a simple script which selects all canvases in my document. I want to loop through them and adjust their width and height.

I was hoping someone could explain how I can access the properties of the canvas so I can change them. I tested it with this:

var d = document.getElementsByTagName('canvas');
for (var i=0, max=d.length; i < max; i++) {
  console.log(d[i].style.width); // blank
}

The problem is, my console.log shows blank lines, so I'm a bit confused. I hope you can explain where I am going wrong here.

dda
  • 6,030
  • 2
  • 25
  • 34
Sir
  • 8,135
  • 17
  • 83
  • 146

1 Answers1

2

canvases have width and height properties which you can get and set, these represent the actual drawing area:

var d = document.getElementsByTagName('canvas');
for (var i = 0, max = d.length; i < max; i++) {
    console.log(d[i].width); // 300 per default
}

Fiddle

Reference

Using CSS or inline style would simply scale the drawing area, similar to CSS width/height applied to an image, while the actual drawing area would be kept the same.

And to get the actual area the canvas takes in the document, that is, computed width/height taking in consideration padding and border, you can use d[i].offsetWidth/offsetHeight, though I believe this is not what OP intended. More details on this here.

Community
  • 1
  • 1
Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
  • If i resize the canvas will i need to change any thing with the context too ? – Sir May 22 '13 at 00:46
  • @Dave Changing those properties seem to wipe off the drawing context though, you usually set those properties before starting to drawn and, in case you need to change proportions after having something drawn, use CSS tricks such as `transform:scale` or [`clip`](https://developer.mozilla.org/en-US/docs/Web/CSS/clip) for example. `=]` – Fabrício Matté May 22 '13 at 00:52
  • Yeh i was about to say it causes it to go black. But one option is to just call draw again on resize. – Sir May 22 '13 at 00:57
  • @Dave Oh yes that is smarter and less hackish. `=]` – Fabrício Matté May 22 '13 at 00:57