Checking for multiple images loaded

后端 未结 7 2227
死守一世寂寞
死守一世寂寞 2021-02-20 09:26

I\'m using the canvas feature of html5. I\'ve got some images to draw on the canvas and I need to check that they have all loaded before I can use them.

I have declared

7条回答
  •  情话喂你
    2021-02-20 09:54

    Can't you simply use a loop and assign the same function to all onloads?

    var myImages = ["green.png", "blue.png"];
    
    (function() {
      var imageCount = myImages.length;
      var loadedCount = 0, errorCount = 0;
    
      var checkAllLoaded = function() {
        if (loadedCount + errorCount == imageCount ) {
           // do what you need to do.
        }
      };
    
      var onload = function() {
        loadedCount++;
        checkAllLoaded();
      }, onerror = function() {
        errorCount++;
        checkAllLoaded();
      };   
    
      for (var i = 0; i < imageCount; i++) {
        var img = new Image();
        img.onload = onload; 
        img.onerror = onerror;
        img.src = myImages[i];
      }
    })();
    

提交回复
热议问题