1

I am trying to use p5.js for my project, but I have a problem figuring out how I could invoke the setup() and draw() functions in a callback function.

My code looks something like this:

const sentence = "was a French statesman and military leader who rose led several successful close"
let formats = ["jpg", "png", "gif", "jpeg"]
let images = []

const separate_words = (sentence) => sentence.split(" ")

const width = window.innerWidth

const imageExists = (url, callback) => {
  var img = new Image();
  img.src = url;
  img.onload = () => { callback(true); };
  img.onerror = () => { callback(false); };
}


const build_canvas = (array_of_img_urls) =>{
  function setup() {
    createCanvas(width, 300);
    images = array_of_img_urls.map(url => loadImage(url))
  }

  function draw() {
    images.forEach(img => {
      image(img, 0, 0, img.width/images.length, img.height/images.length);
    })
  }
}

let items_processed = 0

formats.forEach((format, indexFormat, arrayFormat)  => {
  separate_words(sentence).forEach((name, indexWord, arrayWords) => {
    imageExists(`./images/${name}.${format}`, (exists) => {
      if(exists)
        images.push(`./images/${name}.${format}`)

      items_processed++
      if(items_processed === (arrayWords.length * arrayFormat.length)){
        build_canvas(images)
      }
    })
  })
})

As you can see, I am creating an array of functioning routes to images and then trying to get those images to be displayed in the canvas, using the 5p.js library.

My question is, is there a way to invoke those functions in a callback, or will I have do some back end in Node and once thats loaded, insert the data in?

Charlie Wallace
  • 1,810
  • 1
  • 15
  • 17
Jousi
  • 456
  • 4
  • 26

1 Answers1

1

You should not call setup() or draw() yourself. You should let P5.js call them for you automatically. Normally this would happen naturally when the P5.js library was loaded.

It looks like you should probably refactor your code so you don't have to call the setup() or draw() functions. Here's a rough idea:

var images = [];

function setup(){
    // load images
}

function draw(){
   // draw images
}
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107