Why does this code here successfully draw a green rectangle on html5 canvas,
<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>
while this code does not...
<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>
In the first the code is contained within a function which is called at the bottom of the script, but I don't see why this should make a difference.
<canvas id="canvas"></canvas>is actually rendered in the page.