调整浏览器大小后如何获取画布的宽度和高度

时间:2014-01-24 05:47:15

标签: javascript css html5 html5-canvas

我想获得响应的画布的宽度和高度。我在一个页面上有5个画布元素。

在绘图之前使用Javascript我想知道画布的高度和宽度,以便能够以正确的尺寸绘制图像。

HTML代码:

<div id='container'>
  <div class='all'>
    <canvas id='clock1' style="border:solid">
  </div>
  <div class='all'>
    <canvas id='clock2' style="border:solid">
  </div>
  <div class='all'>
    <canvas id='clock3' style="border:solid">
  </div>
  <div class='all'>
    <canvas id='clock4' style="border:solid">
  </div>
  <div class='all'>
    <canvas id='clock5' style="border:solid">
  </div>
</div>

CSS:

#container
{
    width:100%;
    height:100%;
    position:relative;
}

.all
{
    width:30%;
    height:45%;
    float:left;
}

canvas
{
    width:100%;
    height:100%;
}

1 个答案:

答案 0 :(得分:2)

通常你不使用CSS设置画布的大小,而是计算w / h并使用width和height属性。

但是如果使用CSS,您可以使用getComputedStyle()获取CSS设置的canvas 元素的计算大小:

Online demo

var cs     = getComputedStyle(canvas);
var width  = parseInt( cs.getPropertyValue('width'), 10);
var height = parseInt( cs.getPropertyValue('height'), 10);

此处的大小由getPropertyValue()作为字符串返回,并以像素大小(即“400px”)返回,因此我们使用parseInt()来剪切“px”部分。

然后只需在画布上设置宽度和高度并更新其内容。

完整示例(根据需要调整):

window.onresize = updateCanvas;

updateCanvas();

function updateCanvas() {

    var cs = getComputedStyle(canvas);
    var width = parseInt(cs.getPropertyValue('width'), 10);
    var height = parseInt(cs.getPropertyValue('height'), 10);

    canvas.width = width;
    canvas.height = height;

    var ctx = canvas.getContext('2d');
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(width, height);
    ctx.moveTo(0, height);
    ctx.lineTo(width, 0);
    ctx.stroke();
}
相关问题