仅在图像加载时继续循环

时间:2015-06-14 11:47:12

标签: javascript image object canvas onload

function readXML(){
    var xmlDoc = loadXML();
    var x = xmlDoc.getElementsByTagName("image");
    for (i = 0; i < x.length; i++) {
        if (i == 600){
            break;
        }
        var path = x[i].getElementsByTagName("path")[0].childNodes[0].nodeValue;
        var title = x[i].getAttribute("class");
        this.imageArray.push(new InfoImage(path,title));
        while(this.imageArray[i].isImageLoaded() == false); //something like this
        console.log(this.imageArray[i].getMaxPixels());

    }
}

function InfoImage(path,title){
    this.path = path;
    this.title = title;
    this.color = undefined;
    this.maxPixels = undefined;
    this.imageLoaded = false;

    this.init = function(){
        var canvas = document.querySelector("canvas");
        var img_Color = new Image_Processing_Color(canvas);
        var img = new Image();
        var info_image = this;
        img.onload = function () {
            img_Color.init(img);
            info_image.color = img_Color.getDominantColor();
            info_image.maxPixels = img_Color.getDominantColorPixels();
            info_image.imageLoaded = true;
        };
        img.src = path;
    };

    this.isImageLoaded = function(){
        return this.imageLoaded;
    }

    this.getPath = function(){
        return this.path;
    };

    this.getTitle = function(){
        return this.title;
    };

    this.getColor = function(){
        return this.color;
    };

    this.getMaxPixels = function(){
        return this.maxPixels;
    };

    this.init();
}

我希望我的for循环仅在img.onLoad完成时继续下一次迭代。 while我使用阻止代码并且不会让img.onLoad完成。有没有办法做到这一点?不改变代码结构。

2 个答案:

答案 0 :(得分:0)

您可以查看img的.complete属性:

var x = document.getElementById(“myImg”)。complete; 结果可能是真或假

答案 1 :(得分:0)

如果我理解正确,我相信你最好的选择就是使用async.parallel(如果你想要它是连续的,它们有它的功能 - 系列)。

此功能可以为您执行一系列任务,并在完成时发出回调(在此情况下您会收到错误通知)。