P5js Image Selection Drop-down

Struggling to create a dropdown menu in p5js that showcases images. Facing issues with loading images, unlike in other sketches where the problem did not occur. Seeking a fresh perspective to resolve this error. Appreciate any assistance!

let picker; 
let drum1, drum2, drum3, drum4, drum5;
let img;
let drumType = 'what';

function setup() {
    createCanvas(windowWidth, windowHeight);

    drum1 = loadImage('drum1.jgp');
    drum2 = loadImage('drum2.jpg');
    drum3 = loadImage('drum3.jpg');
    drum4 = loadImage('drum4.jpg');
    drum5 = loadImage('drum5.jpg');

    textAlign(CENTER);
    background(200);
  
    picker = createSelect();
 
    picker.position(10, 10);

    picker.option('djembe');
    picker.option('two hand drums');
    picker.option('one hand drum');
    picker.option('Talking drum');
    picker.option('five hand drums');
   
    picker.changed(pickEvent);

    img = drum5;
}

function draw() {
    background(200, 220, 10);
    textAlign(LEFT);
    image(img, 0, 0, width, height);
    text(trim + ' is a good drum', 10, 50); // look up what trim is

}

function pickEvent() {
    // get the item chosen with .value()
    drumType = picker.value();
        
    if (drumType === 'djembe') {
        img = drum1;
    } else if (drumType === 'two hand drum') {
        img = drum2;
    } else if (drumType === 'one hand drum') {
        img = drum3;
    } else if (drumType === 'talking drum'){
        img = drum4;
    } else  {
        img = drum5;
    }

}https://i.sstatic.net/pBc7dLXf.jpg https://i.sstatic.net/YkgaDzx7.jpg https://i.sstatic.net/UmXUufqE.jpg https://i.sstatic.net/E49GT3SZ.jpg https://i.sstatic.net/vJycb3o7.jpg

Answer №1

There are several issues to address in your code. Here are some important points to consider:

  1. Take your time to code and test each step. Rushing through complex code without testing can lead to a lot of errors that are difficult to untangle all at once. It's better to break down large problems into smaller tasks to make debugging easier.

    Instead of trying to work with all 5 images at once, start by getting one loaded, then two, and so on.

  2. Errors are helpful and should be fully acknowledged. They pinpoint the exact problem areas in your code. Programs that misbehave without any errors are much harder to troubleshoot.

  3. If your images are not loading, ensure they are hosted on a development server.

  4. Make sure all variables are defined before use. An undefined variable like trim can crash your program.

  5. When dealing with a series of tasks like thing1, thing2, ... thing5 or multiple if-else if statements, utilize data structures and loops for scalability instead of hardcoding the tasks.

  6. For loading images, utilize the preload function to ensure they are ready when your app runs.

  7. Separate data from logic. Storing image data in an array of objects instead of hardcoded values makes the program more adaptable and flexible.

  8. Keep variables scoped locally whenever possible. Avoid making them global unless absolutely necessary. This helps improve code organization and readability.

Here's an optimized version of your code:

// TODO: add your own images; these are samples
const images = [
  {
    name: "djembe",
    url: "https://picsum.photos/id/1/100",
  },
  {
    name: "two hand drums",
    url: "https://picsum.photos/id/2/100",
  },
  {
    name: "one hand drum",
    url: "https://picsum.photos/id/3/100",
  },
  {
    name: "talking drum",
    url: "https://picsum.photos/id/4/100",
  },
  {
    name: "five hand drums",
    url: "https://picsum.photos/id/5/100",
  },
];
let selectedImage = images[0];
let select;

function preload() {
  for (const e of images) {
    e.image = loadImage(e.url);
  }
}

function setup() {
  createCanvas(windowWidth, windowHeight);
  select = createSelect();
  select.position(10, 10);
  select.changed(handleSelected);
  images.forEach(e => select.option(e.name));
}

function draw() {
  background(200, 220, 10);
  image(selectedImage.image, 0, 30, 100, 100);
  text(`${selectedImage.name} is a good drum`, 120, 50);
}

function handleSelected() {
  selectedImage = images.find(e => e.name === select.value());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.10.0/p5.js"></script>

Consider optimizing the code further by reducing unnecessary redraws and conserving resources:

const images = [
  {
    name: "djembe",
    url: "https://picsum.photos/id/1/100",
  },
  {
    name: "two hand drums",
    url: "https://picsum.photos/id/2/100",
  },
  {
    name: "one hand drum",
    url: "https://picsum.photos/id/3/100",
  },
  {
    name: "talking drum",
    url: "https://picsum.photos/id/4/100",
  },
  {
    name: "five hand drums",
    url: "https://picsum.photos/id/5/100",
  },
];
let selectedImage = images[0];
let select;

function preload() {
  for (const e of images) {
    e.image = loadImage(e.url);
  }
}

function setup() {
  createCanvas(windowWidth, windowHeight);
  select = createSelect();
  select.position(10, 10);
  select.changed(handleSelected);
  images.forEach(e => select.option(e.name));
  noLoop();
}

function draw() {
  background(200, 220, 10);
  image(selectedImage.image, 0, 30, 100, 100);
  text(`${selectedImage.name} is a good drum`, 120, 50);
}

function handleSelected() {
  selectedImage = images.find(e => e.name === select.value());
  draw();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.10.0/p5.js"></script>

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

Preparing data before using Kendo UI upload function is essential

I need to pass a data (specifically a GUID) to the upload method of the kendoUpload, so that a particular MVC Controller action method can receive this data each time the upload occurs. $("#propertyAttachmentUpload").kendoUpload({ async: { ...

ES6 Class Directive for Angular 1.4

I am currently exploring the possibility of incorporating a directive from version 1.4 and adapting it to resemble a 1.5 component. By utilizing bindToController and controllerAs, I aim to integrate the controller within my directive rather than using a se ...

Strange behavior in Vue observed. The v-if directive is not properly monitoring changes

I am facing a perplexing issue. I have a basic service and a Vue component. In the template, there is a v-if directive that monitors a variable in the service (if it is true, a div should be displayed, otherwise not). Everything works fine when I initial ...

How to call two functions in React, passed as props, one after the other

I am currently working with two React class components. Component1 acts as the parent of Component2, where two functions (functionA and B) are passed in props from Component1 to Component2. Within the nested structure of Component2, there is a function cal ...

AngularJS: Unable to preserve the data

I'm currently working on an issue with saving updated functions using angularJS. I've managed to edit the data and update it on the database side, but the changes aren't reflecting on the frontend side unless I logout and login again. I need ...

Function in React not being successfully passed down between functional components

I have been accustomed to using class components and now I am transitioning into functional components in order to become more proficient with hooks. However, I have encountered an issue where I am struggling to pass a function from one functional compone ...

Hide panel when button is clicked - bootstrap

Is it possible to make a panel collapse by clicking a regular bootstrap button? Below is the code snippet: <div class="panel panel-primary" style="border-color: #464646;"> <div class="panel-heading" style="border-color: #BBBBBB; height: 35px; ...

Minimize CPU consumption in your threejs application

I've been working on a project where I'm coding Snake in Threejs (I know there are simpler methods). Everything works smoothly until the snake reaches a certain size, causing CPU usage to spike to 50% or more and freezing the entire browser tab. ...

Select a random character from a string using JavaScript

This question sets itself apart from Removing random letters from a string as it focuses on selecting a random letter from a string in JavaScript without removing any characters. The goal is to implement a code that picks random letters from a string in J ...

The clash between two jQuery plugins featuring identical function names

I have encountered a dilemma while working on a large website that includes two conflicting jQuery plugins for autocomplete functionality. The first plugin is jquery.autocomplete.js (not part of jQuery UI) which defines the autocomplete function like this ...

Having issues with setting state for an array in ReactJS

I am currently working on a component called Inbox which includes a checkbox feature. However, I am facing an issue where the checkbox only works on the third click and fails to respond on the first and second clicks. The setState function seems to be wo ...

creating a JSON object in PHP that can be easily parsed by JavaScript

In my project, I have an extensive list of items, each item further divided into four sub-items. While it's convenient for me to organize this data in nested arrays using PHP, I encounter issues when trying to transfer them as a JSON object to the cli ...

The Jquery slider panel seems to be stuck open even after I switched its CSS orientation from right to left

I am following up on a previous question, which can be found here. After fixing the jQuery code, I decided to change the panel slider to open from the left side instead of the right. I modified the class from "cd-panel from-right" to "cd-panel from-left". ...

Guidelines for executing a PHP script upon a button click

I am new to learning PHP. I have a jQuery code that I need to implement in PHP. The active class simply changes display:none to display:block. You can find the code here. $(document).ready(function(){ $(".cecutient-btn").click(function(){ event. ...

Looping through nested arrays in an array of objects with Angular's ng-repeat

I'm struggling to access an array within an array of objects in my AngularJS project. Here's the HTML: <li ng-repeat="ai in main.a2"> <div np-repeat="bi in ai.b"> <span ng-bind="bi"></span>b2 </div> </l ...

Styling in CSS is being applied to a button element within a React component,

Having trouble with a button styled with the className 'actions' The button displays the CSS styling from '.actions', but not '.actions button'. Both should be applied. This code snippet works for all elements ...

How can I use ReactJS to find the nearest five locations in order from closest to farthest?

I'm in the process of creating a website for searching nearby locations. I am facing an issue where I want to display the 5 closest locations from my current location in ascending order, but I keep getting the same location result. I need these locati ...

What are the implications of using eval() to interpret function parameters?

I've recently utilized Hopscotch to create a interactive tour on my Website. To implement this, you need to create a JavaScript object as a parameter to trigger the startTour() function which will kick off the tour. For instance, in this case, the tou ...

Using Firebase Authentication in Next.js with Server-Side Components

As I explore how to implement authentication using Firebase in my Next.js app, one thing that stands out is the need to initialize Firebase with our configuration details (apiKey, etc.). The concern I have is when using any Firebase function from a client ...

Delete Entries in MongoDB Collection According to Unique User Pairs

I have a collection of messages stored in MongoDB and I need to keep only the latest 500 records for each pair of users. Users are identified by their sentBy and sentTo attributes. /* 1 */ { "_id" : ObjectId("5f1c1b00c62e9b9aafbe1d6c&quo ...