未捕获的TypeError:无法读取未定义的属性'getContext'

时间:2016-02-25 21:27:07

标签: javascript

我收到此错误“Uncaught TypeError:在运行脚本时无法读取未定义的属性'getContext'。似乎变量“画布”未定义,但我无法弄清楚原因。

var world = {
    canvas: document.getElementById("myCanvas"),
    context: this.canvas.getContext("2d"),
    centerX: this.canvas.width / 2,
    centerY: this.canvas.height / 2,
    drawShape: function (shape) {
        if (typeof shape.draw() === "function")
            shape.draw();
    }
};

2 个答案:

答案 0 :(得分:1)

我在canvas字面之外声明变量world并且它正在工作

答案 1 :(得分:0)

对象文字不会为this建立上下文,因此您无法在其文字定义中将对象称为this

在您的情况下,this.canvas.getContext可能会被评估为window.(undefined).getContext,因为window没有canvas属性。

您可以保存对canvas属性的引用,并避免this

var world = {
    canvas: (var canvas = document.getElementById("myCanvas")),
    context: canvas.getContext("2d"),
    centerX: canvas.width / 2,
    centerY: canvas.height / 2,
    drawShape: function (shape) {
        if (typeof shape.draw() === "function")
            shape.draw();
    }
};