简体   繁体   English

如何更改画布的宽度或高度?

[英]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. 问题是,我的console.log显示空白行,所以我有点困惑。 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: canvas具有您可以获取和设置的widthheight属性,它们代表实际的绘图区域:

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. 使用CSS或内联style将仅缩放绘图区域,类似于应用于图像的CSS宽度/高度,而实际绘图区域将保持不变。

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. 要获得画布在文档中占用的实际面积,即考虑到paddingborder计算出的width / height ,可以使用d[i].offsetWidth / offsetHeight ,尽管我相信这不是OP的目的。 More details on this here . 更多详情请参见这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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