繁体   English   中英

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

[英]Uncaught TypeError: Cannot read property 'getContext' of undefined

我在运行脚本时收到此错误“ Uncaught TypeError:无法读取未定义的属性'getContext'”。 似乎变量“ canvas”是未定义的,但我不知道为什么。

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();
    }
};

我在world文字之外声明了可变canvas ,它正在工作

对象常量不建立上下文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();
    }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM