为什么这里的这段代码成功在html5画布上绘制了一个绿色矩形,
<script type="text/javascript">
function getStart(){
var canvas = document.getElementById('canvas');
if (!canvas) {
alert('Error: Cannot find the canvas element!');
return;
}
if (!canvas.getContext) {
alert('Error: Canvas context does not exist!');
return;
}
var ctx = canvas.getContext('2d');
ctx.fillStyle = "#3d3";
ctx.fillRect(0, 0, 100, 100);
}
getStart();
</script>
虽然这段代码没有......
<script type="text/javascript">
var canvas = document.getElementById('canvas');
if (!canvas) {
alert('Error: Cannot find the canvas element!');
return;
}
if (!canvas.getContext) {
alert('Error: Canvas context does not exist!');
return;
}
var ctx = canvas.getContext('2d');
ctx.fillStyle = "#3d3";
ctx.fillRect(0, 0, 100, 100);
</script>
首先,代码包含在脚本底部调用的函数中,但我不明白为什么这会有所作为。