Creating distinctive, unchanging colors for individual ellipses within a collection in p5.js

It's clear that each ellipse is part of a wave object, with the fill color applied on every frame causing a blinking effect. I'm trying to assign a random color to each ellipse when it's drawn, so it maintains that fill color instead of changing with each frame. Despite my efforts, I haven't been able to achieve this. Any assistance would be greatly appreciated.

class Wave {
  constructor(amp, period, phase) {
    this.amplitude = amp;
    this.period = period;
    this.phase = phase;
  }

  evaluate(x) {
    return sin(this.phase + (TWO_PI * x) / this.period) * this.amplitude;
  }

  update() {
    this.phase += 0.05;
  }
}

let waves = [];
    let y;

function setup() {
  createCanvas(600, 400);
  for (let i = 0; i < 5; i++) {
    waves[i] = new Wave(random(20, 80), random(100, 600), random(TWO_PI));
  }
}

function draw() {
  background(0);

  for (let x = 0; x < width; x += 10) {
    for (let wave of waves) {
    y = wave.evaluate(x);
    noStroke();
    fill(random(255), random(255), random(255));
    ellipse(x, y + height / 2, 6);
    }
  }

  for (let wave of waves) {
    wave.update();
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>

Answer №1

Make a selection of approximately 20 different colors for each wave. Use color() function to create the colors:

for (let i = 0; i < 5; i++) {
    waves[i] = new Wave(random(20, 80), random(100, 600), random(TWO_PI));
    colors = [];
    for (let j = 0; j < 20; j++) {
        colors.push(color(random(255), random(255), random(255)))
    }
    waves_colors.push(colors);
}

Utilize these chosen colors to draw the waves. Employ the % (modulo) operator to determine the remainder of an integer division. The sequence of colors repeats after every 20 points:

for (let i = 0; i < 5; i++) {
    wave = waves[i];
    colors = waves_colors[i];
    for (let j = 0; j < width/10; j ++) {
        x = j*10;
        y = wave.evaluate(x);
        fill(colors[j % colors.length]);
        ellipse(x, y + height / 2, 6);
    }
}

class Wave {
  constructor(amp, period, phase) {
    this.amplitude = amp;
    this.period = period;
    this.phase = phase;
  }

  evaluate(x) {
    return sin(this.phase + (TWO_PI * x) / this.period) * this.amplitude;
  }

  update() {
    this.phase += 0.05;
  }
}

let waves = [];
let waves_colors = [];
let y;

function setup() {
    createCanvas(600, 400);
    for (let i = 0; i < 5; i++) {
        waves[i] = new Wave(random(20, 80), random(100, 600), random(TWO_PI));
        colors = [];
        for (let j = 0; j < 20; j++) {
            if (i % 2 == 1)
                colors.push(color(0, 0, 255, random(128,255)));
            else
                colors.push(color(random(255), random(255), random(255)))
        }
        waves_colors.push(colors);
    }
}

function draw() {
    background(0);
    
    noStroke();
    for (let i = 0; i < 5; i++) {
       wave = waves[i];
       colors = waves_colors[i];
       for (let j = 0; j < width/10; j ++) {
            x = j*10;
            y = wave.evaluate(x);
            fill(colors[j % colors.length]);
            ellipse(x, y + height / 2, 6);
        }
    }

    for (let wave of waves) {
      wave.update();
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.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

Implementing clickable actions to add new entries in a React.js application (using Redux toolkit)

I am currently working on my PET project using Redux toolkit and encountering some issues with inputs. When I add an input on click, it gets added correctly, but I am unsure if it is being added in the right place (it should be added in the ITEMS array). A ...

Are the orders of events maintained when emitted using an event emitter?

I have a simple query regarding the event emitter, which is crucial for my program's logic. Currently, I am utilizing an external library that triggers events that I'm listening to. These events consist of 'data' and 'error'. ...

Showcasing diverse content with an Angular Dropdown Menu

I'm currently developing an angular application, and I've encountered a difficulty in displaying the user's selection from a dropdown menu. To elaborate, when a user selects a state like Texas, I want to show information such as the period, ...

Tips for integrating material UI sample snippets into a component

I have a specific goal in mind: to create a page with a header that says "Survey Start" followed by a user selection interface. My vision is to implement a simple component as follows: export class Survey extends Component { state = { } ren ...

The smooth scrolling feature fails to function properly in Lenis when clicking on links with specified IDs

Is there a reason why the scroll-behavior: smooth property doesn't function properly when Lenis library for smooth scrolling is included? It seems to work fine when the Lenis code is commented out, but once it's added back in, the scrolling isn&a ...

Utilizing React Views in an Express Environment

I am struggling to find a simple example that demonstrates how to connect an Express.js route to render a React view. This is what I have tried so far. +-- app.js +-- config | +-- server.js +-- routes | +-- index.js +-- views | +-- index.html app. ...

Save the language code (ISO 639) as a numerical value

Currently, I'm working with a MongoDB database and have made the decision to store certain information as Numbers instead of Strings for what I thought would be efficiency reasons. For instance, I am storing countries based on the ISO 3166-1 numeric s ...

JWT - Effective strategies for enhancing the user experience for a returning logged-in user

My client authentication system involves storing a JWT in `localStorage` once the user is verified. However, I'm not satisfied with the current user experience when a returning user is redirected straight to a new page without warning. window.locatio ...

Unraveling the Mystery of @Input and @Output Aliases in Angular 2

After researching about the @Input() and @Output() decorators, I discovered that we have the option to use an alias instead of the property name for these decorators. For example: class ProductImage { //Aliased @Input('myProduct') pro ...

What is the best way to utilize "exports" in package.json for TypeScript and nested submodules?

Looking to leverage the relatively new "exports" functionality in Node.js/package.json for the following setup: "exports": { ".": "./dist/index.js", "./foo": "./dist/path/to/foo.js" } so that ...

Converting an array of objects to an array based on an interface

I'm currently facing an issue with assigning an array of objects to an interface-based array. Here is the current implementation in my item.ts interface: export interface IItem { id: number, text: string, members: any } In the item.component.ts ...

Checking the existence of a user's email in Node.js

Hey there! I am new here and currently learning Node.js with Express. I'm trying to find a way to check if a user's email already exists in the database. Here is what I have so far: const emailExists = user.findOne({ email: req.body.email }); if ...

Utilizing Server-Sent Events to display a interactive navigation button

Currently, I am managing a web-based point of sale system where some buttons are hidden for specific functions. To streamline the process, I would like to allow managers to simply click on an "Enable" button in the admin panel and have it immediately refle ...

Attempting to retrieve nested data, only to be met with an undefined response

I've been attempting to retrieve specific information by iterating through the SearchResult object like so: for (let productKey in SearchResult) { if (SearchResult.hasOwnProperty(productKey)) { products.push({ name ...

Tips for bringing in and taking out data in Vue

I have a set of files called total.vue and completeness.vue. I aim to display the chart from total.vue within completeness.vue, which is my designated admin dashboard where I plan to feature 2 or 3 additional charts. For this task, I will be exporting con ...

How can I effectively monitor and track modifications to a document's properties in MongoDB?

I'm wondering how to effectively track the values of a document in MongoDB. This involves a MongoDB Database with a Node and Express backend. For example, let's say there is a document within the Patients collection: { "_id": "4k2lK49938d ...

NodeJS error: Attempted to set headers after they have already been sent to the client

As a beginner, I have encountered an error message stating that the API is trying to set the response more than once. I am aware of the asynchronous nature of Node.js but I am struggling to debug this issue. Any assistance would be greatly appreciated. rou ...

Using Typescript to remove an element from an array inside another array

I've encountered an issue while trying to remove a specific item from a nested array of items within another array. Below is the code snippet: removeFromOldFeatureGroup() { for( let i= this.featureGroups.length-1; i>=0; i--) { if( this.featureGr ...

Tips for working with elements in WebDriver that are created dynamically by JavaScript

As a novice in automation using Java and WebDriver, I find myself facing a particular issue: Browse for a specific customer Select a new customer type from a dropdown menu Click on the Save button Outcome: Upon trying to change the customer, a message p ...

How can I omit extra fields when using express-validator?

Currently, I am integrating express-validator into my express application and facing an issue with preventing extra fields from being included in POST requests. The main reason for this restriction is that I pass the value of req.body to my ORM for databas ...