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?