[英]“Uncaught TypeError: Cannot read property 'getContext' of undefined” when drawing on canvas
[英]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.