【问题标题】:js image.onload call method on parentjs image.onload 在父节点上调用方法
【发布时间】:2012-09-01 01:51:03
【问题描述】:

我正在制作一个网络应用程序,在这里我从网络加载图像并显示它们。我正在使用 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 制作一个 Kinetic Image。然后在加载实际图像时,将图像更改为该新图像。

谢谢! -巴勃罗

【问题讨论】:

    标签: javascript kineticjs


    【解决方案1】:

    将自定义变量分配给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);
        }
    

    【讨论】:

    • 谢谢,这行得通。好吧,它设置了一切正确,虽然由于某种原因图像没有改变......只有当我转到不同的选项卡,然后返回它才会改变。所以我想它不会被重绘,如果你知道如何做到这一点,那就太好了。虽然这个答案是正确的:D
    • @TheOddler 你试过 drawImage() 函数了吗:kineticjs.com/docs/symbols/Kinetic.Shape.php#drawImage ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 2012-02-09
    相关资源
    最近更新 更多