matski
matski

Reputation: 541

correct way to use loadImage in p5.js?

I'm loading image URLs from a json file. I have everything working fine, except displaying the actual images.

It's a simple clik carousel. Hit the click and it moves index onto the next one. I want to make sure the images display at the same time, obviously but it's not working (images are referenced, but don't display).

Anyone know what I am doing wrong?

var w = window.innerWidth;
var h = window.innerHeight;
var xPos = w/2;
var yPos = h/2;
var index = 0;
var imageData;
var imgList = [];
var indexMax;

function preload() {
  loadJSON("image_search_result.json", resultLoaded);
}

function resultLoaded(data) {
  imageData = data;
  indexMax = imageData.items.length;
  for (i = 0; i < indexMax; i++) {
    imgList.push(imageData.items[i]['link']);
  }
}

function mouseReleased() {
  index = index + 1;
  if (index == indexMax){
    index = index - indexMax;
  }
}

function setup() {
  createCanvas(w,h);
}

function draw() {
  background(0);
  image(loadImage(imgList[index]),xPos,yPos,w,h);
  text(index,20,60); // index counter
  text(imgList[index],80,60); // image list number
  textSize(20);
  fill(255);
}

Upvotes: 2

Views: 2985

Answers (2)

matski
matski

Reputation: 541

Finally I got this to work by adding a callback in loadImage. I was unaware you could do this (hadn't seen it referenced in any documentation), but it works very efficiently.

function draw() {
  nextImg = loadImage(imgList[index], imageLoaded);
  text(index,20,60); // index counter
  text(imgList[index],80,60); // image list number
  textSize(20);
  fill(255);
}

function imageLoaded() {
  background(0);
  image(nextImg,xPos,yPos,w,h);
  imageMode(CENTER);
}

Upvotes: 0

Niccol&#242; Caselli
Niccol&#242; Caselli

Reputation: 882

I think the problem is that you're trying to upload images every call to the drawing function. As you wrote the code, even if the images to be uploaded will always be the same, p5.js will reload them from scratch. You should load them before starting the program. As I did below:

var w = window.innerWidth;
var h = window.innerHeight;
var xPos = w / 2;
var yPos = h / 2;
var index = 0;
var imageData;
var imgList = [];
var indexMax;

function preload() {
  loadJSON("img.json", resultLoaded);
}

function resultLoaded(data) {
  imageData = data;
  indexMax = imageData.items.length;
  for (i = 0; i < indexMax; i++) {
    url = imageData.items[i]["link"];
    imgList.push(loadImage(url));
  }
}

function mouseReleased() {
  index = index + 1;
  if (index == indexMax) {
    index = index - indexMax;
  }
}

function setup() {
  createCanvas(w, h);
}

function draw() {
  background(0);

  image(imgList[index], xPos, yPos, w, h);

  text(index, 20, 60);
  textSize(20);
  fill(255);
}

P.S. @George Profenza gave the same answer while I was writing the code. Sorry

Upvotes: 2

Related Questions