Reputation: 497
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.
Upvotes: 0
Views: 51
Reputation: 5144
Internet Explorer does allow to reffer the HTML elements by their IDs. If you have an html element with id="canvas" on the page IE will have a global variable "canvas" which points to that html element. That can be a reason of the problem
In first case you have defined variable inside of a function, so it doesn't conflict with global one. In second case the variable is global, so both your variable and browser created one shares the same name, which can lead to problems.
All above is specific for Internet Explorer, must not cause any problems in other browsers.
Upvotes: 0
Reputation: 382122
If your code isn't in a function, the return
statement can't work because it has nothint to return from. They generate an error
Uncaught SyntaxError: Illegal return statement
or
SyntaxError: return not in function
(depending on the browser)
Upvotes: 1
Reputation: 3411
Are the second script runs in body section and after canvas tag?
javascript cant use the tag until it will be loaded in the DOM, so you have to put your script section after the tag
Upvotes: 2