javascript - 无法使用 Canvas 读取 null 的属性 'getContext'

标签 javascript html canvas

我收到错误 Uncaught TypeError: Cannot read property 'getContext' of null 并且文件中的重要部分是......我想知道因为 game.js 在下面的目录中,它不能找到 Canvas ?我该怎么办?

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

最佳答案

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

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

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

或者干脆把你的js放在<canvas>之后.

关于javascript - 无法使用 Canvas 读取 null 的属性 'getContext',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10291693/

相关文章:

javascript - 在 resolve() 抛出错误后重定向到模板时出现 Angular UI Router 问题

html - 背景图像缺失 window.print

jquery - Bootstrap Form Helpers 国家和州不显示

javascript - 如何使用原始选择选项值更新 Bootstrap 选择数据原始索引

javascript - 如何将外部 Javascript 代码设置为可配置?

javascript - PHP Loop with jQuery hide/slide toggle (Repeater field WP)

javascript - 在 JavaScript 中检测最新的浏览器版本

android - 如何增加 Android 中的 Canvas 大小?

javascript - 当脚本放置在 head 标签内时,为什么 HTML5 Canvas 不绘制?

java - Canvas 中的 MouseListener 不工作