我想我有一個類似的問題,this question,但我想了解如何使用回調函數,以及如何實現它爲我的特定情況一點幫助。我試圖讓圖像按需「繪製到畫布上,即任何時候調用某個函數。圖像與我稱之爲塊的對象相關聯。塊有尺寸,座標和網址。Javascript使用回調畫一個圖像到畫布
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
function Block(x, y, width, height, url) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.url = url;
this.drawBlock = drawBlock;
function drawBlock() {
var blockSprite = new Image();
blockSprite.src = url;
blockSprite.onload = context.drawImage(blockSprite,x,y,width,height);
}
}
您可以看到演示here。奇怪的是,如果我鏈接到網絡上的圖像,它會工作,但如果我鏈接到我的磁盤上的圖像失敗。我相信這是因爲onload事件發生在drawBlock被調用之前,而且我需要使用回調函數或承諾來解決這個問題,但我對Javascript很陌生,所以我想在這裏稍微介紹一下。任何幫助或建議,將不勝感激。
嘗試用'的window.onload =函數週圍代碼(){};' – James
@JamesBrown其實,我已經有我周圍的所有代碼。一旦他們準備好了,我就會將一些東西繪製到畫布上,而且它的一部分工作正常。 – Era