javascript之HTML5 Canvas + javascript 类 = 错误

jyk 阅读:113 2026-10-07 19:25:01 评论:0

我正在尝试为包含 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
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号