Computing the size of a <canvas> on load?
<html>
<head>
<style type="text/css">
canvas { width: 100%; height: 100%; }
</style>
<script>
function init() {
canvas = document.getElem开发者_如何学JAVAentById('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?
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:
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.
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
and height
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/
<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>
Do not use the onload function in body, but you can use window.onload instead:
<html>
<head>
<script>
function onLoadDoIt()
{
alert(document.getElementById("mydiv"));
}
window.onload = onLoadDoIt;
</script>
</head>
<body>
<div id="mydiv">test</div>
</body>
</html>
精彩评论