user1356896
user1356896

Reputation:

looping through images in javascript

I have a plugin that rotates 360 degrees around a set of images (300 to be precise). I want to know if I can use a for in loop or a for loop to cycle through all the images. Right now It's setup like this.

$("#spin").spritespin({
        width     : 510,
        height    : 327,
        frames    : 10,
        image     : [
                "360rotation/000.jpg",
                "360rotation/001.jpg",
                "360rotation/002.jpg",
                "360rotation/003.jpg",
                "360rotation/004.jpg",
                "360rotation/005.jpg",
                "360rotation/006.jpg",
                "360rotation/007.jpg",
                "360rotation/008.jpg",
                "360rotation/009.jpg",
                  ],

        animate   : true,
        loop      : true,
        frameTime : 60,
        fadeFrames : 20,
        fadeInTime : 0,
        fadeOutTime : 120
      });

This works but I don't want to type out all 300 images. How can I do this faster?

Upvotes: 0

Views: 329

Answers (2)

Drazen
Drazen

Reputation: 2826

Maybe something like

var images = new Array();

for (i = 0; i < (n = 301); i++) {
  images.push("360rotation/00" + i + ".jpg")
}

$("#spin").spritespin({
    width     : 510,
    height    : 327,
    frames    : 10,
    image     : images,

    animate   : true,
    loop      : true,
    frameTime : 60,
    fadeFrames : 20,
    fadeInTime : 0,
    fadeOutTime : 120
  });

Upvotes: 0

David Thomas
David Thomas

Reputation: 253318

The easiest way, I guess, would be to populate an array based on the known start, and end, images:

function namePad(num){
    if (num < 10){
        return '00' + num;
    }
    else if (num >=10 && num < 100){
        return '0' + num;
    }
    else {
        return num;
    }
}

var imageArray = [];

for (var i=0; i < 300; i++){
    imageArray.push('360rotation/' + namePad(i) + '.jpg');
}

JS Fiddle proof of concept.

Upvotes: 2

Related Questions