2012-08-31 32 views
0

我正在製作一個web應用程序,在這裏我從網絡載入圖像並顯示它們。我正在使用KineticJS。 我所做的是我首先做一個預加載,其中我加載一個「加載」圖像,直到實際圖像加載並準備顯示後才顯示。js image.onload父母的調用方法

所以,這裏是我的代碼:

function CardObject(cardName) 
{ 
this.name = cardName; 

this.tapped = false; 

// Create kinetic image with loading image 
this.image = new Kinetic.Image({ 
     x: 10, 
     y: 10, 
     image: CardLoadingImage, 
     width: CardWidth, 
     height: CardHeight 
    }); 

// Add actual image, and when loaded change it 
this.imageObj = new Image(); 
this.imageObj.onload = function() //Problem here 
{ 
    this.image.setImage(this.imageObj); 
} 
this.imageObj.src = "testImage.jpg"; 

// Add it to the stage 
this.layer = new Kinetic.Layer(); 
this.layer.add(this.image); 
Stage.add(this.layer); 
} 

雖然,什麼是錯與imageObj我的onload功能。我得到的錯誤:Uncaught TypeError:不能調用undefined的方法'setImage'

當我在我的調試器中看到,函數中的「this」是該圖像對象,而不是我的卡...這不是什麼我預計,無論我需要什麼。我如何解決這個問題?

所以它要做的是,首先用我的loadingImage製作一個Kinetic Image。然後,當加載實際圖像時,將圖像更改爲新圖像。

謝謝! -Pablo

回答

2

指定一個自定義變量this,然後使用該自定義變量或使用jquery proxy

function CardObject(cardName) 
    { 
    this.name = cardName; 

    this.tapped = false; 
    var that = this;//assigning custom variable 

    // Create kinetic image with loading image 
    this.image = new Kinetic.Image({ 
      x: 10, 
      y: 10, 
      image: CardLoadingImage, 
      width: CardWidth, 
      height: CardHeight 
     }); 

    // Add actual image, and when loaded change it 
    this.imageObj = new Image(); 
    this.imageObj.onload = function() //Problem here 
    { 
     that.image.setImage(this);//edited 
    } 
    this.imageObj.src = "testImage.jpg"; 

    // Add it to the stage 
    this.layer = new Kinetic.Layer(); 
    this.layer.add(this.image); 
    Stage.add(this.layer); 
    } 
+0

謝謝,這個作品。好吧,它設置一切正確,但由於某種原因圖像不會改變......只有當我去到不同的標籤,然後回來它會改變。所以我想它不會被重新繪製,如果你有任何想法如何做到這一點會很好。雖然這個答案是正確的:D –

+0

@TheOddler你試過drawImage()函數:http://www.kineticjs.com/docs/symbols/Kinetic.Shape.php#drawImage? – Ankur