Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I get the error Uncaught TypeError: Cannot read property 'getContext' of null and the important parts in files are... I am wondering since game.js is in a directory below, it cannot find canvas? What should I do?

./index.html:

<canvas id="canvas" width="640" height="480"></canvas>

./javascript/game.js:

var Grid = function(width, height) {
        ...
        this.draw = function() {
        var canvas = document.getElementById("canvas");
        if(canvas.getContext) {
            var context = canvas.getContext("2d");
            for(var i = 0; i < width; i++) {
                for(var j = 0; j < height; j++) {
                    if(isLive(i, j)) {
                        context.fillStyle = "lightblue";
                    }
                    else {
                        context.fillStyle = "yellowgreen";
                    }
                    context.fillRect(i*15, j*15, 14, 14);
                }
            }
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
496 views
Welcome To Ask or Share your Answers For Others

1 Answer

I guess the problem is your js runs before the html is loaded.

If you are using jquery, you can use the document ready function to wrap your code:

$(function() {
    var Grid = function(width, height) {
        // codes...
    }
});

Or simply put your js after the <canvas>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...