Undefined Ctx Variable
Solution 1:
It's all about scope, the variable will only exist in the block of code it is defined. Move your definitions to the top of the code.
var tiles = Array("1.png","0.png");
var loaded = 0;
var loadTimer;
var ctx;
var canvas;
functionloadimg(){
var tileImg = newArray();
for(var i=0;i<tiles.length;i++){
tileImg[i] = newImage();
tileImg[i].src = tiles[i];
tileImg[i].onload = function(){
loaded++;
}
}
}
functionloadall(){
if(loaded == tiles.length){
clearInterval(loadTimer);
loadTimer = setInterval(gameUpdate,100);
}
}
functiongameUpdate(){
ctx.clearRect(0,0,canvas.width,canvas.height); //line 32draw();
}
functioninit(){
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
loadimg();
loadTimer = setInterval(loadall,100);
}
Solution 2:
As you define ctx
within the init-function, ctx
will be private to that function, thus not available at line 32. The execution stops at ctx
, since it isn't available inside gameupdate()
, therefore you don't get an error about canvas
(yet!). If you make ctx
available to all functions by declaring it outside the init-function, your error will move to the canvas-variable (since that is private to init-function as well), stating that canvas
isn't declared.
To make the variables available to all functions, do the declaration at the top of your script, outside the function. Then remove the var
keyword from you init-function and simply assign the variables instead:
var ctx, canvas;
// ... all your functionsfunctioninit(){
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
loadimg();
loadTimer = setInterval(loadall,100);
}
For more information on variable scoping in JavaScript, have a look at this MDN article.
Solution 3:
I can only guess, but in order for this to work:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
You need to have a
<canvas id="canvas"></canvas>
Element in your html.
Otherwise, getElementById("canvas")
will not return a canvas and canvas.getContext("2d");
will not set the ctx var.
EDIT: also see DJohnson's post regarding the scope of your canvas and ctx variables.
If you omit the var keyword, the scope of a variable will be global. see: Javascript variable scope
In your sample, you have defined it locally using
function init(){
var ctx = canvas.getContext("2d");
}
That is why you cannot access it in another function (and that is also what is different from the reference you posted).
So this would work:
function init(){
ctx = canvas.getContext("2d"); // not var keyword
}
And this would be proper:
var ctx;
function init(){
ctx = canvas.getContext("2d");
}
Post a Comment for "Undefined Ctx Variable"