[英]“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.