Samuel Newport Samuel Newport - 5 months ago 21
Javascript Question

javascript Class only calling function once

I have a problem with my code in which I have a

setinterval
loop that checks whether a variable
menuScreen == true
if it does then it creates a new object (or prototype) called gameMenu1 and sets itself to false again.

Under this in the loop is a try and catch statement that attempts to call the
gameMenu1.Draw();
function.

When I set
menuScreen
to =
true
it will run this draw function once and then just not run it again and i have no idea why.

Javascript Code:

//defining the canvas elements (initial setup)
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;

//setting the menuScreen to true
var menuScreen = true;
var gameScreen = false;


//gamemenu class
var GameMenu = function () {
// inserting a texture from files
this.img = new Image();
this.img.src = "Assets/textures/TitleScreen.png";
};

GameMenu.prototype.Draw = function () {
console.log('drawn to screen (menuscreen)')
ctx.drawImage(this.img,0,0,canvas.width,canvas.height);
};

setInterval(function() {
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.strokeRect(0,0,canvasWidth,canvasHeight);
console.log(menuScreen)
if (menuScreen == true) {
var gameMenu1 = new GameMenu();
menuScreen = false;
}
try {
gameMenu1.Draw();
}
catch(err) {

}

}, 30);


Cavas Element:

<canvas id="canvas" width="600" height="600"></canvas>

Answer

Thats it,

setInterval(function() {
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.strokeRect(0,0,canvasWidth,canvasHeight);
    console.log(menuScreen)
    var gameMenu1;

    if (menuScreen == true) {
        gameMenu1 = new GameMenu();
        menuScreen = false;
    }  

    try {
        gameMenu1.Draw();
    } catch(err) {

    }

}, 30);