繁体   English   中英

HTML5 canvas + JavaScript类=错误

[英]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.contextundefined并且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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM