簡體   English   中英

Javascript:我無法在畫布上繪制圖像

[英]Javascript: I cannot draw image on the canvas

我已經在頁面上創建了畫布,但是當我嘗試在畫布上導入圖像時,它沒有出現,這是我使用的代碼。 (makeGameArea是我創建的用於在網頁上制作畫布的方法,該方法的代碼未顯示,因為將其放置在此處太長了)

以下是應該有問題的以下代碼

var myGameArea2 = makeGameArea(700, 150, "myArea", "white");
var myContext2 = myGameArea2.getContext("2d");

var myImage = new drawImage(myContext2, "sonic.gif", 91, 97, 0, 0);
myImage.draw();

function drawImage(ctx, src, width, height, x, y){
     this.image = new Image();
     this.image.src = src;
     this.width = width;
     this.height = height;
     this.x = x;
     this.y = y;
     this.draw = function(){
         this.image.onload = function(){                  
             ctx.drawImage(this.image, this.x, this.y, this.width, this.height); 
         }
     }           

}

我的drawImage()方法有什么問題嗎?

HTMLImage。 每個src設置onload只會觸發一次。

在這里,您將您的處理程序附加到draw方法中,我猜稍后會調用它。 此時,該事件將已經觸發,因此將不會被調用,因為除非您重置其src否則它將不會再次觸發。

固定代碼塊:

function drawImage(ctx, src, width, height, x, y){
     this.image = new Image();
     this.width = width;
     this.height = height;
     this.x = x;
     this.y = y;
     this.draw = function(){
        ctx.drawImage(this.image, this.x, this.y, this.width, this.height));
        };
     // if you want it to draw as soon as possible
     this.image.onload = this.draw.bind(this);
     this.image.src = src;
     }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM