Proper technique for utilizing loadImage in p5.js?

I've been working on loading image URLs from a json file and everything seems to be functioning correctly, except for the actual images not displaying.

Currently, I have a simple click carousel set up where clicking moves the index to the next image. However, despite referencing the images in the code, they just won't display as intended.

If anyone has any ideas on what I might be doing wrong here, please let me know!

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);
}

Answer №1

It seems like the issue lies in your attempt to upload images with each call to the drawing function. Your code is set up in a way that even if the images remain constant, p5.js will continuously reload them from scratch. To resolve this, you should preload the images before initiating the program, as demonstrated 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);
}

Side note: @George Profenza also provided a similar solution while I was crafting this code. Apologies for any redundancy.

Answer №2

Success! After implementing a callback in loadImage, I was able to get everything working smoothly. This method wasn't something I had come across before, but it turned out to be incredibly effective.

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to navigate to a different page when scrolling in React Router?

I am working on a design that includes a landing page with 100vh and 100vw dimensions. I want it to transition into another page as the user scrolls down. How can I achieve this using React hooks and React Router? Any guidance or suggestions would be high ...

Is there a workaround for Angular ui-sref param removing spaces?

Looking for help with an anchor tag: <a ui-sref="view({id:{{ id }}})" data-toggle="tooltip" data-placement="top" title="View Details"><i class="fa fa-search-plus fa-2x icon-color"></i></a> The issue I'm facing is with the id ...

Having issues with the basic KnockoutJS binding not functioning as expected

There appears to be an issue with my KnockoutJS script that I'm struggling to pinpoint. Below is the snippet of HTML code: <h2>SendMessage</h2> <div class="form-group" id="messageSender"> <label>Select User Type</l ...

Navigating an array and organizing items based on matching properties

When I receive an array that looks like this: errors = [ { "row": 1, "key": "volume", "errorType": "Data type", "expectedType": "number", &quo ...

Struggling to retrieve the accurate input value when the browser's return button is clicked?

Having multiple forms created for different conditions, each one submits to a different page. However, when I navigate back from the other page, all my forms display the same values as before. Here's the code snippet: <form action="<?php echo b ...

Creating dynamic forms using AngularJS and the ng-repeat directive

i am working with AngularJS dynamic forms . According to my userid value i generated multiple form field with same model name using ng-repeat. i am not able to get this input model values due to this ng-repeat. in this example i am using static userid data ...

Meteor.js in conjunction with ScrollMagic TweenMax.to

Having trouble getting Meteor template.rendered to work with ScrollMagic I am trying to make this code function properly. if (Meteor.isClient) { Meteor.startup(function () { scrollMagicController = new ScrollMagic(); Template.StartAnimatio ...

Ways to insert text into an SVG file

I am currently using vue-svg-map with a USA map. I am trying to display the state code (path.id) on my svg map. Can anyone provide guidance on how to achieve this? <radio-svg-map v-model="selectedLocation" :map="usa" :location-class="getLocation ...

Adding an Ajax response to a div in HTML: A step-by-step guide

How can I add Ajax response to a div in my HTML code? Below is my ajax script: $(document).ready(function(){ $('.credit,.debit').change(function(){ var value=$(this).val(); $.ajax({ type:"POST", url:" ...

populate first and then aggregate all the data in mongoose

My goal was to first populate and then aggregate data Comps.find().populate({ path : "reviews", model : "Review" }).exec(function(err, populatedData){ if(err) console.log(err) console.log("populatedData--", populate ...

Working with npm objects across multiple files

My goal is to integrate the npm package for parallax (lax.js) into my project. The documentation states that in order to initialize it, the following code snippet should be included: window.onload = function () { lax.init() // Add a driver that we use ...

Unusual behavior observed within for loop; code within not running as expected

I will be presenting my code along with some images to illustrate the issue at hand. Something as simple as declaring a variable or using the log function results in the json being undefined. Upon entering text into the input field, the ajax call is trigg ...

Eliminate the excess padding from the Material UI textbox

I've been struggling to eliminate the padding from a textbox, but I'm facing an issue with Material UI. Even after setting padding to 0 for all classes, the padding persists. Could someone provide guidance on how to successfully remove this pad ...

Placing a component within a .jsx file instead of utilizing a .css file for positioning

Seeking a way to position a component within a .jsx-file, rather than a .css-file, to accommodate multiple instances of the same component performing various tasks on different parts of the page. Avoiding duplication of files with minor CSS class changes, ...

Guide on configuring Angular validation to trigger on blur events and form submission

Validation in Angular is currently set to update on model change, but this method can be unfriendly for user interface as it displays errors upon keyup. An optimal solution would involve displaying error messages on blur and also on form submission. After ...

Enhancing your react-slick carousel with a captivating full-screen background

I need assistance with implementing a full screen slider using react-slick. I am facing difficulty in adding an image as the background. My code snippet looks like this: import image1 from "../assets/bg1.png" import image2 from "../ ...

Bidirectional Data Flow with rxjs in Angular

After adapting an Angular template and component from Angular Material's dashboard schematic, I wanted to manipulate the properties on the "cards" object using events and two-way data binding. Initially, it seemed like two-way data binding was working ...

Tips for increasing character limit when moving data from a MYSQL database to an Excel spreadsheet with dropdown menus using PHP

I'm facing an issue while trying to export my MySQL data to an Excel file as a dropdown list. The problem arises when the string limit exceeds 255 characters, causing the Excel file to become corrupted. Below is the snippet of my code: foreach ($sequ ...

Developing JavaScript functionality to manage multiple radio buttons that should be hidden after being selected

I am currently in the process of building a comprehensive form that includes numerous radio buttons. My goal is to present one question at a time, which means using JavaScript to hide the respective div after a radio button has been clicked. While I have ...