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

please see example below
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:

http://jsfiddle.net/PQS3A/7/

You had several problems with your example:

  1. A <div> does not have height or width attributes. You need to set those through CSS.
  2. 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 to position:relative (or absolute or fixed).
  3. The width and height 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.

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;
}

Html相关问答推荐

使用Scrapy Select 最后一个子文本

如何让一个动态列表以网格方式水平显示

Select 包含iframe的图形<><>

在css嵌套 Select 器中,尾随的`&;‘是什么意思?

需要关于HTML的建议

为什么在添加文本时网格区域会调整大小?

如何创建剪切到路径的循环文本字幕?

CSS Grid:使网格行填充屏幕,将下一行推离屏幕

浏览器是否可以呈现存储在代码点0x09处的字形?

使用单个粗体字符串向段落添加页边空白

当多个a元素用作目标时的:target伪类

如何使用 Flutter 构建 Chrome 扩展?

如何使用html css将图像显示为附加形状

CSS flex:0 0 auto创建了1像素的间隙

Flex布局中,当父元素高度较高时,交叉轴上出现额外的空白问题.