Upload multiple canvas images through javascript loop

前端 未结 4 1339
感情败类
感情败类 2021-01-28 17:36

I am trying to make an upload script which resizes multiple images client side before the saveimage.php handles them. The reason for this is because they will be upload

4条回答
  •  -上瘾入骨i
    2021-01-28 17:46

    JavaScript loads image asynchronously. That means once it is assigned a new image's .src it will begin loading the image but will simultaneously continue processing the javascript after the .src while the image takes time to load.

    You're using the same image variable (var img) inside your for loop. Therefore, each time through the loop you are overwriting the previous img before the previous image has been fully loaded.

    Here's an image loader that fully loads all image and then calls the start() function where you can do you processing:

    // image loader
    
    // put the paths to your images in imageURLs[]
    var imageURLs=[];  
    imageURLs.push("myImage1.png");
    imageURLs.push("myImage2.png");
    // etc, etc.
    
    // the loaded images will be placed in imgs[]
    var imgs=[];
    
    var imagesOK=0;
    loadAllImages(start);
    
    function loadAllImages(callback){
        for (var i=0; i=imageURLs.length ) {
                    callback();
                }
            };
            img.onerror=function(){alert("image load failed");} 
            img.crossOrigin="anonymous";
            img.src = imageURLs[i];
        }      
    }
    
    function start(){
    
        // the imgs[] array now holds fully loaded images
        // the imgs[] are in the same order as imageURLs[]
    
    }
    

提交回复
热议问题