jsimage.onload调用父对象上的方法

js image.onload call method on parent

本文关键字:方法 对象 onload 调用 jsimage      更新时间:2023-09-26

我正在制作一个网络应用程序,在这里我从网络加载图像并显示它们。我正在使用KineticJS。我所做的是首先进行预加载,在预加载中我加载一个"加载"图像,直到实际图像加载并准备好显示为止。

所以,这是我的代码:

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函数有问题。我得到错误:未捕获类型错误:无法调用未定义的方法"setImage"

当我在调试器中查看时,函数中的"this"是那个图像对象,而不是我的卡。。。这不是我所期望的,也不是我所需要的。我该怎么解决?

所以它要做的是,首先用我的loadingImage制作一个动态图像。然后,当加载实际图像时,将图像更改为该新图像。

谢谢!-Pablo

将自定义变量分配给this,然后使用该自定义变量或使用jquery代理

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);
    }