gpt4 book ai didi

javascript - HTML5 Canvas + javascript 类 = 错误

转载 作者:行者123 更新时间:2023-11-28 01:20:49 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com