0

I'm very new to coding, specially .js and also to Stack.

So I have this code and I would like to change the images to a local folder instead of picsum. I've searched and tried but couldn't do it. Is there a way to load the images from a local folder in a way that doesn't slowdown the program?

Hope I've done it right and you can understand my question!

let imgs = [];
let num = 15;

function preload() {

  for (let i = 0; i < num; i++) {
    imgs[i] = loadImage("https://picsum.photos/400/400/?image=" + i * 10);
  }
}


function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  angleMode(DEGREES);
}

function draw() {
  background(0,0,0);
  orbitControl();
  push();
  translate(0, 0, -500);
  let n = 0;
  for (let j = 0; j < 20; j++) {
    for (let i = 0; i < 20; i++) {
      
      let x = map(i, 0, 20, -500, 500);
      let y = map(j, 0, 20, -500, 500);
      
      let z = sin(frameCount + j*10 + i * 10)*350+350;
      push();
      translate(x, y, z);
      texture(imgs[n]);
      plane(50, 50);
      n = (n + 1) % imgs.length;
      pop();
    }
  }
  pop();
}
<html>
    <head>
    <script src="mySketch.js" type="text/javascript"></script><script src="https://cdn.jsdelivr.net/npm/p5@0.7.2/lib/p5.min.js" type="text/javascript"></script>
    </head>
<body>
</body>

</html>
JZon
  • 1

1 Answers1

0

This will give you a dictionary with a key and an image corresponding to it. For example, images["imagefile1.png"] will return an image with src imagefile1.png.

const IMAGES_FILES = [
  "imagefile1.png",
  "imagefile2.png"
];

const images = {};
const downloadPromiseImage = Promise.all(IMAGES_FILES.map(downloadImage));

function downloadImage(imageName) {
  return new Promise((resolve) => {
    const image = new Image();
    image.onload = () => {
      images[imageName] = image;
      resolve();
    };

    //  add path to image directory. This path should be relative to your entry HTML file.
    image.src = `./Images/${imageName}`;
  });
}

Promise.all([downloadPromiseImage]).then(() => {
   // do whatever with images dictionary
})
  • Thank you so much! But I don't know if I can get it though... Is much more complex. I will try! Should I add this before preload or inside preload? – JZon Dec 23 '20 at 03:08
  • I'd just make sure that you download your images before you start rendering. I would put Promise.all([downloadPromiseImage]).then(() => {//your setup code here} in your setup function and delete the preload. – Brayden Werner Dec 23 '20 at 03:34
  • I couldn't get it after all. But I'll get back to it, need some practice! Thanks a lot – JZon Dec 30 '20 at 03:07