使用img.src将链img.onload链接到Image()对象

时间:2017-11-20 10:13:50

标签: javascript jquery html css image

我有一个能够读取&#34;图像链接的功能&#34;与foreach(项目)迭代。在每次迭代中,我尝试:在Image()对象中加载图像,在onload事件中加载属性(naturalWidth&amp; naturalHeight)并将其粘贴到DOM中作为背景<DIV>

然而img.onload是异步的,在onload事件粘贴之前,所有迭代都将通过。

如何在每次迭代中创建连续的img.onload链和更改img.src?

function singleGrid() {
  galdiv1.className = galClassList;

  function imgFill() {
    arr.forEach(function(item) {
      img = new Image();
      img.onload = function() {
        var nHeight = this.naturalHeight;
        var nWidth = this.naturalWidth;
        var res = nWidth / nHeight;
        console.log("image source: " + arr[i] + ", naturalWidth: " + nWidth + "px, naturalHeight: " + nHeight + "px");
        blockres = width * res;
        var div = divCreate(blockres);
        galdiv1.append(div);
      };
      img.src = item;##
      Heading##
    }, this);
  }
  imgFill();
}

1 个答案:

答案 0 :(得分:1)

var imageURLS = [];
var imageTags = [];

// Runs once when all images are loaded
function onAllImagesLoaded() {

}

// Individual image loaded Successfully
function onImageLoad() {
    this.hasLoaded = true;

    for (var i = 0; i < imageTags.length; ++i) {
        if (!imageTags[i].hasLoaded) {
            return; // Exit the function if any image hasn't loaded yet
        }
    }

    onAllImagesLoaded();
}

// Individual image failed to load
function onImageError() {
    console.warn("Error: image " + this.id + " could not be retrieved");
    this.hasLoaded = true;

    for (var i = 0; i < imageTags.length; ++i) {
        if (!imageTags[i].hasLoaded) {
            return;
        }
    }

    onAllImagesLoaded();
}

function loadImages() {
    var newImageTag = null;

    for (var i = 0; i < imageURLS.length; ++i) {
        newImageTag = new Image();
        newImageTag.id = i; // Give each Image a unique identifier (Helps to find ones that don't load properly if you have any problems)
        newImageTag.hasLoaded = false; // Add new 'hasLoaded' flag
        newImageTag.onload = onImageLoad; // Set event handlers, It's better to use an existing function instead of an inlined one
        newImageTag.onerror = onImageError; // This is because an inlined function will create a closure when called
        newImageTag.src = imageURLS[i]; // This starts the async loading
        imageTags.push(newImageTag);
    }
}