JavaScript load Images in an Array and Show in Image Source

我与影子孤独终老i 提交于 2019-12-08 18:15:35

Your example is incomplete. You need to show what the imageItem constructor does (and it's convention to use a capital letter for the first character in a constructor), so:

function ImageItem(src) {
  this.image = new Image();
  this.src = src.
}

should do the job here. You also seem to want imgArray as a global, so declare it as one:

var imgArray;

function initialize(){
    //add our 10 images to our array 
    imgArray[imageNum++] = new imageItem(imageDir + "armory.jpg");

Assigning an array literal is a bit easier:

    imgArray = [ new ImageItem(imageDir + "armory.jpg"),
                 new ImageItem(imageDir + "eddy.jpg"),
                 ...
                 new ImageItem(imageDir + "...")
    ];
}

var totalImgs = imgArray.length;

Though I can't see why you don't just assign the array literal directly and not bother with the wrapper function. The startImage function can be a bit tidier:

function startImage(){
    document.getElementById("pic").src = imgArray[0].src;
}

Accessing element properties directly is more reliable across browsers and less to type than using setAttribute (which has quirks in some browsers).

appcropolis

Load multiple images sounds like a functionality that you might want to user in different projects. I would suggest to create a function that can process your images array and append the image object to a DIV:

var images = [
    'path/to/image1.png',
    'path/to/image2.png',
    'path/to/image3.png',
    'path/to/image4.png',
    'path/to/image5.png'
];

function loadImages(imgArr, targetId){
    for(var i=0; i< imgArr.length; i++) {
        console.log(imgArr[i]);
        var img = new Image();
            img.src = imgArr[i];
        document.getElementById('output').appendChild(img);
    }
}

loadImages(images);

You can also invode the loadImage() function from yout button:

<button onclick="loadImages(images)">Start</button>

Modify your javascript function like this and see.

function startImage(){

    document.getElementById("pic").src =  imgArray[0].src;
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!