javascript - HTML5 Canvas + javascript 类 = 错误

标签 javascript html class canvas drawimage

我正在尝试为包含 2 个 Canvas 元素的区域编写一个 javascript 类,其中 1 个用于背景,1 个用于前景。 但是当我点击 Canvas 时出现错误:

“未捕获类型错误:无法读取未定义的属性“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 没有 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 .

关于javascript - HTML5 Canvas + javascript 类 = 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23281511/

相关文章:

javascript - 对所有页面使用相同的 Handlebars 模板

javascript - Angularfire ngRoute/解决问题,跳转到否则

javascript - Extjs:Element 的上/下功能如何工作?

html - 邮箱——如何模拟绝对定位

html - 如何在同一行的相对两侧放置图标?

java - 类构造函数在类中不可见

javascript - 使用带有 browserSettings.proxyConfig 的 firefox webextension 设置代理

html - 在 IE 中导航到数据 URI

html - 全尺寸背景中的边距

Swift For In Loop 遍历一组自定义类不起作用