【问题标题】:Make chain img.onload with img.src to Image() object将 img.onload 与 img.src 链接到 Image() 对象
【发布时间】:2017-11-20 10:13:49
【问题描述】:

我有一个函数能够通过 foreach(item) 迭代读取“图像链接”数组。在每次迭代中,我都试图:在Image() 对象中加载图像,并在 onload 事件中获取属性(naturalWidthnaturalHeight)并将其粘贴到 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();
}

【问题讨论】:

  • 您是否尝试加载所有图像,然后将它们附加到 DOM?
  • @MrSmith Yap。我想预先加载所有图像以获取每个图像 naturalWidth 和 naturalHeight 的 Image() 属性。用于计算每个 DIV 的背景宽度和高度,我将在其中附加此图像。我可以把它现在如何在带有 Inspector 代码的 chrome 中工作的屏幕截图发给你吗?

标签: javascript jquery html css image


【解决方案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);
    }
}

【讨论】:

  • 尝试在里面发布这个)谢谢你花时间在我身上,如果出现问题,请尝试评论
猜你喜欢
  • 1970-01-01
  • 2019-02-22
  • 1970-01-01
  • 2020-07-30
  • 2012-04-25
  • 2016-11-25
  • 1970-01-01
  • 2015-09-27
  • 1970-01-01
相关资源
最近更新 更多