简体   繁体   中英

How do I alter a canvas' width or height?

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.

canvas es 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM