【发布时间】:2022-02-22 13:12:56
【问题描述】:
所以我认为代码
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Log Canvas Width</title>
<style>
#canvas {
background: #888888;
width: 600px;
height: 600px;
}
</style>
<script>
function draw() {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
document.write(canvas.width);
}
</script>
</head>
<body onload="draw();">
<canvas id='canvas'>
Canvas not supported
</canvas>
</body>
</html>
打印 300 而不是 600,因为 <body onload="draw();"> 使脚本在页面加载时运行,而此时画布尚未捕获修改后的值 (600)。
然后我将代码修改为:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Log Canvas Width</title>
<style>
#canvas {
background: #888888;
width: 600px;
height: 600px;
}
</style>
</head>
<body>
<canvas id='canvas'>
Canvas not supported
</canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
document.write(canvas.width);
</script>
</body>
</html>
现在我想象脚本在画布从嵌入样式中获取属性之后运行,我将看到 600。不正确。即使画布的 width = 600,我仍然得到 300。发生了什么?
【问题讨论】:
标签: javascript html canvas