计算
<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>
此代码显示设置样式之前的尺寸。我需要款式确定后的尺寸。我该怎么做?
<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>
This code displays the size before it has been styled. I need the size after it has been styles. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的问题源于画布的固有尺寸和它占用的 CSS 像素数量之间的差异。 HTML 规范 说:
这意味着,就用于绘制图像的坐标而言,您的画布默认的绘图空间为 300x150px。但是,您的 CSS 规则会将画布拉伸到页面的大小(至少在宽度方面)。逻辑上仍然只有 300px 宽可供绘制,但它将在 100% 的页面宽度对应的位置上进行缩放和物理渲染。
无论如何,
width
和height
属性对应于画布的固有绘图尺寸。由于您关心 CSS 大小,因此可以使用 window.getCompulatedStyle。http://jsfiddle.net/3DDsX/
Your problem stems from the difference between the intrinsic dimensions of the canvas and the number of CSS pixels it takes up. The HTML specification says:
What this means is that your canvas defaults to a drawing space of 300x150px in terms of the coordinates used to draw images. However, your CSS rules will stretch the canvas to the size of the page (at least with regard to width). There will still only be 300px wide to logically draw on, but it will be scaled and physically rendered on whatever 100% of the page width corresponds to.
Anyway, the
width
andheight
properties correspond to the intrinsic drawing dimensions of the canvas. Since you care about the CSS size, you can use window.getComputedStyle.http://jsfiddle.net/3DDsX/
不要在 body 中使用 onload 函数,但可以使用 window.onload 代替:
Do not use the onload function in body, but you can use window.onload instead: