【问题标题】:HTML5 canvas + javascript class = errorHTML5 画布 + javascript 类 = 错误
【发布时间】:2014-06-10 11:35:14
【问题描述】:

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

“未捕获的类型错误:无法读取未定义的属性 '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();
}

【问题讨论】:

标签: javascript html class canvas drawimage


【解决方案1】:

问题在于this 不是您认为的单击处理程序中的内容,这意味着this.contextundefinedundefined 没有drawImage() 方法。尝试使用the .bind() method

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

【讨论】:

    【解决方案2】:

    你的问题在于以下几行:

    this.canvas = document.getElementById(canvasElement);
    this.context = this.canvas.getContext("2d");
    

    this.context 未定义。确保以上行返回正确的对象。

    【讨论】:

    • 是的,我知道,但我不明白为什么它是未定义的。我认为画布可以正常访问,因为它已正确调整大小。
    猜你喜欢
    • 2013-10-10
    • 2014-04-06
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    相关资源
    最近更新 更多