在Javascript中使用循环创建和加载图像

Create and Load Images using a loop in Javascript

本文关键字:创建 加载 图像 循环 Javascript      更新时间:2023-09-26

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

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

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

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'];
然后,循环遍历数组中的每个元素,并为每个元素创建一个图像元素。我们将创建image元素,并将其打包到最后的数组中:
//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 (i In imageFiles)可以更有效地执行,但这种类型的循环的优点是它可以用于任何对象(对象、数组、字符串)。在你学习的时候,它是一个很好的通用工具。参见@Web_designer的链接问题,了解for x in y循环可能导致问题的原因。这里的for循环语法几乎是JS中数组循环的"经典香草"。

另外,如果你的图像文件名总是数字和顺序的,你可以利用这一点,但要"计算"它们,而不是预先存储它们。

让我们知道如果有什么你想要更多的细节!

真的很丑,但是你可以使用图像的onload属性来运行一个javascript函数:

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

这个函数可以负责加载下一个图像:

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