我在运行脚本时收到此错误"未捕获的类型错误:无法读取未定义的属性'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();
}
};
我在文字之外声明了变量canvas
world
并且它正在工作
对象文字不会为this
建立上下文,因此您不能在其文字定义中将对象称为this
。
在您的情况下this.canvas.getContext
可能被评估为window.(undefined).getContext
,因为它没有canvas
属性window
。
您可以保存对 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();
}
};