I have a script which keeps telling me ctx is undefined but yet a different variable is still set in the script which was made at the same place… so im confused why one variable is set and not the other.
The error is:
Uncaught ReferenceError: ctx is not defined on line 32 (i commented line 32)
Yet var canvas is defined =/
This is my script:
var tiles = Array("1.png","0.png");
var loaded = 0;
var loadTimer;
function loadimg(){
var tileImg = new Array();
for(var i=0;i<tiles.length;i++){
tileImg[i] = new Image();
tileImg[i].src = tiles[i];
tileImg[i].onload = function(){
loaded++;
}
}
}
function loadall(){
if(loaded == tiles.length){
clearInterval(loadTimer);
loadTimer = setInterval(gameUpdate,100);
}
}
function gameUpdate(){
ctx.clearRect(0,0,canvas.width,canvas.height); //line 32
draw();
}
function init(){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
loadimg();
loadTimer = setInterval(loadall,100);
}
Hope you can help explain my mistake.
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.