使画布宽和高至父 [英] make canvas as wide and as high as parent
问题描述
我想制作一个矩形画布来模拟一个进度条
,但似乎当我设置一个画布的宽度和高度为100%,它不真的使它高和宽父
i would like to make a rectangular canvas to simulate a progress bar but it seems when i set the width and height of a canvas to 100%, it doesn't really make it as high and as wide as parent
请参见下面的示例
http:// jsfiddle。 net / PQS3A /
是否甚至可以制作非方形画布?
我不想硬编码画布的高度和宽度,因为当在更大或更小的屏幕(包括移动设备)中查看时,它应该动态更改
Is it even possible to make non-squared canvas? I don't want to hardcode the height and width of canvas, because it should change dynamically when viewed in bigger or smaller screen, including mobile devices
推荐答案
这是一个修复问题的工作示例:
Here's a working example fixing the problems:
您的示例有几个问题:
-
< div>
没有height
或width
属性。你需要通过CSS设置它们。 - 即使div的大小正确,它使用默认的
position:static
意味着它不是任何孩子的定位父母。如果你想让canvas与div的大小相同,你必须将div设置为position:relative
(或absolute $ c $ 和
)。 Canvas上的c> height
属性指定要绘制的数据的像素数(如图像中的实际像素),并且与 帆布。这些属性必须设置为整数。
- A
<div>
does not haveheight
orwidth
attributes. You need to set those through CSS. - Even if the div were sized correctly, it was using the default
position:static
, which means that it is NOT the positioning parent of any children. If you want the canvas to be the same size as the div, you must set the div toposition:relative
(orabsolute
orfixed
). - The
width
andheight
attributes on a Canvas specify the number of pixels of data to draw to (like the actual pixels in an image), and are separate from the display size of the canvas. These attributes must be set to integers.
链接到上面的示例使用CSS设置div大小,并将其设置为定位父级。它创建一个JS函数(如下所示),以便将一个画布设置为与其所在父节点相同的显示大小,然后调整内部 width
和 height
属性,以使其与显示的像素数相同。
The example linked to above uses CSS to set the div size and make it a positioned parent. It creates a JS function (shown below) to both set a canvas to be the same display size as its positioned parent, and then adjusts the internal width
and height
properties so that is has the same number of pixels as it shows.
var canvas = document.querySelector('canvas');
fitToContainer(canvas);
function fitToContainer(canvas){
// Make it visually fill the positioned parent
canvas.style.width ='100%';
canvas.style.height='100%';
// ...then set the internal size to match
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
}
这篇关于使画布宽和高至父的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!