How would I change this from two hardcoded images to an array of images.

Viewed 172

I copied this Pen a while back and had it on my list and finally come to it now. However my knowledge is kind of rusty and i'm a little stuck right now trying to change it from two hardcoded images to a dynamic array of images.

Here is the Pen

I tried adding

var slide3 = new Slide(width, height, 'middle');
    var l3 = new THREE.ImageLoader();
    l3.setCrossOrigin('Anonymous');
    l3.load('/assets/ScreenSaver/space3.jpg', function(img) {
        slide3.setImage(img);
    })
        
    root.scene.add(slide3);

But that wont cut it, it seems i need to add another control variable.

Any tips or advice would be appreciated.

3 Answers

Ended using this, someone achieved this in react and lucky for me i also have the same objective.

Solution

loadNextImages (images, index) {
let first = index
let second
const tmp = (first + 1) % (images.length)
if (index % 2 === 0) {
  second = tmp
} else {
  second = first
  first = tmp
}
this.slide0.setImage(images[first])
this.slide1.setImage(images[second])
return tmp

To add another slide, try this:

      var slide3 = new Slide(width, height, 'in');
  var l3 = new THREE.ImageLoader();
    l3.setCrossOrigin('Anonymous');
    l3.load('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR-5w-Kdidn-qT7gkRKDgQzFmCULZQN-YvwFchCenzPVIkggTif1Q', function(img) {
        slide3.setImage(img);
    })

root.scene.add(slide3);
  tl.add(slide3.transition(), 0);

You missed the last line. Check it working with an extra image here:

https://codepen.io/pmbranco/pen/gdBmyR

A better way to do this would be to create a variable that is an array where each element is the image source, and then load them in dynamically. That way you only need to write that chunk out once. Each time you want to add a new image, take one out, or edit the order, you only need to edit the image array.

var images = ['https://s3-us-west-2.amazonaws.com/s.cdpn.io/175711/winter.jpg', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/175711/spring.jpg'];
  
for (let x = 0; x < images.length; x++) {
  var slide[x] = new Slide(width, height, 'out');
  var l[x] = new THREE.ImageLoader();
  l[x].setCrossOrigin('Anonymous');
  l[x].load(images[x], function(img) {
    slide.setImage(img);
  })
  root.scene.add(slide);

  tl.add(slide[x].transition(), 0);
};

Related