So I've been looking at a couple of examples of how to fill a canvas with some other image, and as soon as I rearrange the code slightly they stop working. I'm noticing some behavior on canvases that doesn't make sense compared to other types of javascript variables, and I'd like to know what's going on. for instance, if I do something like this...
<!DOCTYPE HTML>
<html>
<head>
<script>
var someVar = "This variable has been set";
function aFunction(){
alert(someVar);
};
</script>
</head>
<body onload="aFunction()">
<canvas id="aCanvas" height="100" width="100"></canvas>
</body>
</html>
...I get a pop-up saying "This variable has been set", which is what I would expect, but if I do something like this...
<!DOCTYPE HTML>
<html>
<head>
<script>
var aCanvas = document.getElementById("aCanvas");
var context;
function aFunction(){
try{
context = aCanvas.getContext("2d");
alert("it worked");
}
catch(err){
alert(err);
}
};
</script>
</head>
<body onload="aFunction()">
<canvas id="aCanvas" height="100" width="100"></canvas>
</body>
</html>
...I get an alert with the message "TypeError: aCanvas is undefined"
And yet, if I try to define the canvas the same way within the try itself...
<!DOCTYPE HTML>
<html>
<head>
<script>
var aCanvas;
var context;
function aFunction(){
try{
aCanvas = document.getElementById("aCanvas");
context = aCanvas.getContext("2d");
alert("it worked");
}
catch(err){
alert(err);
}
};
</script>
</head>
<body onload="aFunction()">
<canvas id="aCanvas" height="100" width="100"></canvas>
</body>
</html>
I get the message "it worked"
So if I want to initialze a global variable as a string or something simple, I can then reference it in functions. If I try to initialize a global variable as a canvas, my functions go on to think that it is null. Why is that?