使用canvas无法读取null的属性'getContext' [英] Cannot read property 'getContext' of null, using canvas

查看:421
本文介绍了使用canvas无法读取null的属性'getContext'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到错误未捕获TypeError:无法读取属性'getContext'为null 并且文件中的重要部分是......我想知道因为game.js所在下面的目录,它找不到画布?我该怎么办?

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:

./index.html:

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

./javascript / game.js:

./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);
                }
            }
        }
    }
}


推荐答案

我想问题是在加载html之前你的js运行。

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

如果你使用jquery,你可以使用文档就绪函数来包装你的代码:

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

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

或者只是将你的js放在< canvas>

Or simply put your js after the <canvas>.

这篇关于使用canvas无法读取null的属性'getContext'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆