0
votes

I am trying to spawn creeps on my canvas in a game I am making. The creeps should spawn on the canvas border in four random modes (start of x, start of y, end of x, end of y) and a random value for corresponding x or y from canvas.height or canvas.width. The code will explain it better I think:

//Creep Array- Creep() gets pushed into it later
        var creeps = []

//Random position generation    
        function Creep() {               
            this.XorY = Math.floor(Math.random() * 4)
            console.log("Creep.XorY "+ this.XorY);
            if (this.XorY==0) {
                this.x=10
                this.y=Math.floor(Math.random()*canvas.height)
            }
            //.....
         }
//function Creep() continues with more if conditionals for spawn at X or Y axis
// I am getting error that the property height of undefined in anonymous function 
// Creep cannot be read. This is I think related to the canvas but the canvas var
// is declared at the top and defined later in the script as follows:

        window.onload = function() {
            // Nastavenie premennych
            button = document.getElementById("button")
            text = document.getElementById("text")
            canvas = document.getElementById("canvas")
            ctx = canvas.getContext("2d")
            requestAnimationFrame(mainLoop);
        }

Am I using the random function wrong or is there a problem with the flow of my code? I use the canvas to width and height property to draw my ship and that seems to work fine.

1
Try to use inspector and breakponts to find out why your properties are undefined at a specific moment. If the Creep function is called before the onload events fires then canvas and ctx are null (if defined before as you state)Mir
you seem to generate the initial creeps before the onload. Hence canvas is not defined yet, that's why you get the error : perform all your inits in the onload handler.GameAlchemist

1 Answers

0
votes

Looks like you're trying to use the height of the canvas node in the Creep() function, but you're actually defining the canvas node later in the code.

So when JavaScript tries to read the canvas.height value, canvas isn't defined yet since it will get defined after the page finishes loading (window.onload).

Try putting var canvas = document.getElementById("canvas"); before defining the Creep() function.