HTML5画布&x2B;javascript类=错误

HTML5画布&x2B;javascript类=错误,javascript,html,class,canvas,drawimage,Javascript,Html,Class,Canvas,Drawimage,我试图为一个区域编写一个javascript类,该区域包含2个画布元素,1个用于背景,1个用于前景。 但是当我点击画布时,我得到了一个错误: “未捕获的TypeError:无法读取未定义的属性'drawImage'” 任何帮助都将不胜感激 function GAMEAREA(canvasElement, bgElement) { this.canvas = document.getElementById(canvasElement); this.context = this.ca

我试图为一个区域编写一个javascript类,该区域包含2个画布元素,1个用于背景,1个用于前景。 但是当我点击画布时,我得到了一个错误:

“未捕获的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.canvas = document.getElementById(canvasElement);
this.context = this.canvas.getContext("2d");

此上下文未定义。确保上面的行返回了正确的对象。

问题在于,
不是您认为的单击处理程序中的对象,这意味着
此。上下文
未定义的
并且
未定义的
没有
drawImage()
方法。尝试使用:

…强制
将此
设置为所需的值。或者你可以这样做:

function GAMEAREA(canvasElement, bgElement)
{
    var self = this;
    ...    
    this.onClick = function(e)
    {
        self.context.drawImage(self.pawnImg, 0, 0);
    };    
    ...
}

函数中此
的值取决于该函数的调用方式。有关如何设置此的详细信息,请访问。

,这解释了此如何在JavaScript中工作。是的,我知道,但我无法理解为什么它没有定义。我认为画布是可以访问的,因为它的大小调整正确。
function GAMEAREA(canvasElement, bgElement)
{
    var self = this;
    ...    
    this.onClick = function(e)
    {
        self.context.drawImage(self.pawnImg, 0, 0);
    };    
    ...
}