<html>
<head>
<style type="text/css">
canvas { width: 100%; height: 100%; }
</style>
<script>
function init() {
canvas = document.getElementById('canvas');
alert(canvas.width + "x" + canvas.height);
}
</script>
</head>
<body onload="init();">
<canvas id="canvas"> </canvas>
</body>
</html>
此代码在设置样式之前显示尺寸。我需要样式后的尺寸。我该怎么做?
最佳答案
您的问题源于 Canvas 的固有尺寸与其占用的 CSS 像素数之间的差异。 HTML specification说:
The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.
这意味着根据用于绘制图像的坐标,您的 Canvas 默认为 300x150 像素的绘图空间。但是,您的 CSS 规则会将 Canvas 拉伸(stretch)到页面的大小(至少在宽度方面)。逻辑上仍然只有 300 像素的宽度可供绘制,但它会在对应的 100% 页面宽度上进行缩放和物理渲染。
无论如何,width
和height
属性对应于 Canvas 的固有绘图尺寸。由于您关心 CSS 大小,因此可以使用 window.getComputedStyle .
<head>
<style>
canvas { width: 100%; height: 100% }
</style>
<script>
function init() {
var canvas = document.getElementById('canvas');
var style = getComputedStyle(canvas);
alert(style.width + ' x ' + style.height);
}
</script>
</head>
<body onload="init();">
<canvas id="canvas"></canvas>
</body>
关于javascript - 计算加载时 <canvas> 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5140235/