[英]HTML5 canvas + javascript class = error
我正在嘗試為包含2個畫布元素,一個用於背景和一個用於前景的區域編寫一個javascript類。 但是當我在畫布上單擊時出現錯誤:
“未捕獲的TypeError:無法讀取未定義的屬性'drawImage'”
任何幫助,將不勝感激...
function GAMEAREA(canvasElement, bgElement)
{
this.canvas = document.getElementById(canvasElement);
this.context = this.canvas.getContext("2d");
this.bgCanvas = document.getElementById(bgElement);
this.bgContext = this.bgCanvas.getContext("2d");
this.pawnImg = document.getElementById("pawnImg");
this.init = function()
{
this.adjustSize();
this.canvas.addEventListener("mousedown", this.onClick, false);
};
this.onClick = function(e)
{
this.context.drawImage(this.pawnImg, 0, 0);
};
this.adjustSize = function()
{
this.canvas.height = window.innerHeight - ($("#headerDiv").outerHeight() + $("#footerDiv").outerHeight());
if (this.canvas.height > window.innerWidth) {
this.canvas.height = window.innerWidth;
this.canvas.width = this.canvas.height;
}
else this.canvas.width = this.canvas.height;
this.bgCanvas.height = this.canvas.height;
this.bgCanvas.width = this.canvas.width;
this.bgCanvas.style.display = "block";
this.canvas.style.display = "block";
};
this.init();
}
問題在於this
不是您認為的單擊處理程序中的內容,這意味着this.context
是undefined
並且undefined
沒有drawImage()
方法。 嘗試使用.bind()
方法 :
this.canvas.addEventListener("mousedown", this.onClick.bind(this), false);
......迫使this
給你所需要的價值。 或者,您可以執行以下操作:
function GAMEAREA(canvasElement, bgElement)
{
var self = this;
...
this.onClick = function(e)
{
self.context.drawImage(self.pawnImg, 0, 0);
};
...
}
函數中this
的值取決於該函數的調用方式。 有關如何設置this
設置的更多信息,請訪問MDN 。
您的問題出在以下幾行:
this.canvas = document.getElementById(canvasElement);
this.context = this.canvas.getContext("2d");
this.context
是未定義的。 確保上述行返回正確的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.