2012-08-31 34 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