使帆布与母帆布一样宽,一样高

我想做一个矩形画布来模拟一个进度条 但似乎当我把画布的宽度和高度设置为100% 时,它并没有像父画布那样高,那样宽

请看下面的例子
Http://jsfiddle.net/pqs3a/

有没有可能做出非正方形的帆布呢? 我不想硬编码画布的高度和宽度,因为它应该动态变化时,查看更大或更小的屏幕,包括移动设备

124497 次浏览

Use CSS properties instead of attributes on the tags:

<div style="background-color:blue;width:140px;height:20px">
<canvas style="background-color: red;width:100%;height:100%">
</canvas>
</div>​

That seems to work

Use the width and height attributes of the canvas if you want it to actually be as big as the parent element. You can set them using JQuery.

$(document).ready(function() {
var canvas = document.getElementById("theCanvas");
canvas.width = $("#parent").width();
canvas.height = $("#parent").height();
});

If you do not know JQuery, then use the following Javascript:

var canvas = document.getElementById("theCanvas");
var parent = document.getElementById("parent");
canvas.width = parent.offsetWidth;
canvas.height = parent.offsetHeight;

If you use the css height and width attributes, style="width:100%; height:100%;", then you are just stretching the canvas. This will cause everything you draw on the canvas to look stretched.

JSFiddle for JQuery solution.

JSFiddle for Javascript solution.

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