繁体   English   中英

使用JavaScript中的循环创建和加载图像

[英]Create and Load Images using a loop in Javascript

我很抱歉,但是我是一个严重的新手。

请有人能告诉我如何使用循环加载图像吗?

即重写以下类型的代码以使用循环来自动执行该过程。

function loadimages() {
    pic00 = new Image;
    pic00.src = "images/IMG_0019.jpg";

    pic01 = new Image;
    pic01.src = "images/IMG_0020.jpg";

    pic02 = new Image;
    pic02.src = "images/IMG_0021.jpg";

    pic03 = new Image;
    pic03.src = "images/IMG_0022.jpg";

    pictures = new Array(4);
    pictures[0] = pic00;
    pictures[1] = pic01;
    pictures[2] = pic02;
    pictures[3] = pic03;
}

我见过一些可能描述类似情况的帖子,但恐怕我太笨了,无法理解它们。 任何帮助表示赞赏。

问候

这样可以:

 var URLs = [ "http://placehold.it/128x128.png/f00/400?text=Red", "http://placehold.it/128x128.png/0f0/040?text=Green", "http://placehold.it/128x128.png/00f/004?text=Blue", "http://placehold.it/128x128.png/ff0/440?text=Yellow" ]; var imgs = URLs.map(function(URL) { var img = new Image(); img.src = URL; document.body.appendChild(img); return img; }); 

演示版

对于您的示例,您将需要某种方式来了解每个图像路径/文件名(因为它们不是IMG_001.jpg,002.jpg等)。 一种简单但技术含量较低的方法是将所有文件名打包到一个数组中,以用作我们的源信息:

//Pack the image filenames into an array using Array shorthand
var imageFiles = ['IMG_0019.jpg', 'IMG_0020.jpg', 'IMG_0021.jpg', 'IMG_0022.jpg'];

然后,就需要遍历该数组中的每个元素,并为每个元素创建一个图像元素。 我们将创建图像元素,并一步将其打包到最终数组中:

//Loop over an array of filenames, and create an image for them, packing into an array:
var pictures = []; //Initialise an empty array

for (var i = 0, j = imageFiles.length; i < j; i++) {
    var image = new Image; //This is a placeholder
    image.src = 'images/' + imageFiles[i]; //Set the src attribute (imageFiles[i] is the current filename in the loop)
    pictures.push(image); //Append the new image into the pictures array
}

//Show the result:
console.log(pictures);

编写此代码是为了易于理解,而不是有效。 特别是,for(在imageFiles中的i)可以更有效地完成,但是这种类型的循环的优点是可以在任何对象(对象,数组,字符串)上使用。 这是学习时很好的通用工具。 有关for x in y循环中for x in y可能导致问题的原因,请参见@Web_designer的链接问题。 这里的for循环语法几乎是JS中数组循环的“经典香草”。

另外,如果您的图像文件名总是数字和连续的,则可以利用它,但是“计算”它们,而不是预先存储它们。

让我们知道您是否需要更多详细信息!

确实很丑陋,但是您可以使用图片的onload属性运行javascript函数:

<img id="imgToLoad" onload="loadNextImage();" src="image1.png"/>

该函数可能负责加载下一个图像:

function loadNextImage () {
   document.getElementById( "imgToLoad" ).src = "image2.png";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM