[英]Canvas' Image type in an Array of Javascript Object
下午好,我需要一些關於我的代碼的幫助,我正在嘗試使用用戶可以點擊的Hearts在畫布中編寫地圖,但是我想將這些心臟存儲到數組中以使用for循環顯示它們。
我的代碼在這里:
var canvas = document.getElementById("mapC");
var ctx = canvas.getContext("2d");
var Heart = function(link, posX, posY) {
this.link = link;
this.posX = posX;
this.posY = posY;
this.pic = new Image();
this.pic.addEventListener("load", function() {
ctx.drawImage(this.pic, this.posX, this.posY);
}, false);
this.pic.src = "heart.png";
}
Heart.prototype.heartClick = function()
{
document.location.href= this.link;
}
var heartsArray = new Array();
heartsArray.push(new Heart("this", 40, 40));
問題是
Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'
但我的“this.pic”圖像是數組中可顯示的類型,我沒有找到錯誤,請幫助我。
在你的回調函數中, this
指向全局對象window
。 您應該this
參考保存到新變量,然后您可以使用它。
var self = this;
this.pic.addEventListener("load", function() {
ctx.drawImage(self.pic, self.posX, self.posY);
}, false);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.