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

When NuxtImg is utilized, the image will rotate 90 degrees with Nuxt3 NuxtImg

Recently, I have encountered an issue when using NuxtImg where my images appear rotated by 90°. This problem specifically arises with vertical mobile images that are read from supabase and displayed. Interestingly, the images look fine before uploading th ...

Exploring Nested Divs with Vue Test Utils

Recently, I came across this shallowMounted vue component: <div class="card p-relative"> <div class="card-header"> <div class="card-title h4"> a lovely title <!----> <!----> </div> </div ...

Initiate Ant Design select reset

I am facing an issue with 2 <Select> elements. The values in the second one depend on the selection made in the first one. However, when I change the selected item in the first select, the available options in the second one update. But if a selectio ...

Tips for embedding text into a doughnut chart with primeng/chart.js

Currently tackling a primeng chart project involving the development of a doughnut chart within angular. The task at hand is to display text inside the doughnut chart, aligning with the designated design vision. Referencing the image below for visualizatio ...

Utilizing HTML5 Canvas for Shadow Effects with Gradients

Surprisingly, it seems that the canvas API does not support applying gradients to shadows in the way we expect: var grad = ctx.createLinearGradient(fromX, fromY, toX, toY); grad.addColorStop(0, "red"); grad.addColorStop(1, "blue"); ctx.strokeStyle = gra ...

JavaScript namespace problems

Although I am using a namespace, the function name is getting mixed up. When I call nwFunc.callMe() or $.Test1.callTest(), it ends up executing _testFunction() from the doOneThing instead of the expected _testFunction() in the $.Test1 API. How can I correc ...

Setting a background image as a variable in Vue.js

I am currently working on a vue.js component that includes a div.icon: Vue.component('obj', { props: ['img', 'name'], template: '<div><div class="icon"></div> {{ name }}</div>' }) While ...

For the past 8 hours, my main focus has been on successfully transmitting a basic JSON object containing data from an API from my Express backend to a React component

I have been trying to achieve my initial goal of retrieving data from the API I am using on the backend, inserting that data into my database, and then sending that data through res.json so it can be accessed on the frontend via fetch. Despite all my attem ...

Please do not exceed two words in the input field

I need to restrict the input field to only allow up to two words to be entered. It's not about the number of characters, but rather the number of words. Can this restriction be achieved using jQuery Validation? If not, is there a way to implement it u ...

Retrieve an image from the database and associate it with corresponding features or news in PHP

I have retrieved a value from the database, displayed it as an image, and made it a link. So, I want that when a user clicks on the different image, they get the result from the query related to the image. I hope everyone understands. <?php // Connect ...

Pending activation of the Timer Fired event

Below is some code I have for implementing swipe gesture functionality: this.topSlide = this.elementRef.nativeElement.querySelector('.product_rate_slide'); if (this.topSlide) { this.topSlide.addEventListener('touchstart', this.hand ...

Creating a JavaScript array filled with database data using PHP

Below is a snippet of PHP code used to establish a connection to a database: <?php $host = "localhost"; $user = "admin"; $password = ""; $dbname = "test"; $con = new mysqli($host, $user, $password, $dbname) or die ('Could not connect to the d ...

Unusual class exhibiting peculiar async/await patterns

Node 7.9.0 The situation goes like this: class TestClass { constructor() { const x = await this.asyncFunc() console.log(x) } async asyncFunc() { return new Promise((accept) => { setTimeout(() => accept("done"), 1000) }) ...

bindings and validation of input values in angularjs

In my scenario, I am dealing with a dynamic regExp and unique masks for each input. For instance, the regExp is defined as [0-9]{9,9} and the corresponding mask is XXX-XX-XX-XX. However, when it comes to Angular's pattern validation, this setup is con ...

Vue.js parent component sending new data: prop mutation detected

Encountering an issue in the console with the following error message: Instead, use a data or computed property based on the prop's value. Prop being mutated: "sortType" Within my root file, I have an API and filter function sending data to comp ...

Keystroke to activate Ant Design Select and start searching

I'm currently using the 'react-hotkeys-hook' library and have successfully implemented a hotkey that logs in the console when triggered (via onFocus()). My goal now is to use a hotkey that will open a Select component and add the cursor to i ...

Cannot find JS variable after loop has completed

I am struggling to understand why the value of my variable is not changing in my function. Here is my code snippet: var count = function(datain){ let temparr = [], countobj = {}; $.each(datain, function(key, val) { console.log(temparr); cou ...

Guide to iterating within a loop with a variable number of iterations above or below the specified amount in JavaScript

I am currently engaged in a project for a small theater group, and I am facing challenges with getting this loop to execute properly. <% include ../partials/header %> <div class="jumbotron jumbotron-fluid"> <div class="container"> ...

What could be the reason for my component not getting the asynchronous data?

Currently, I am delving into the intricacies of React and have been following a tutorial that covers creating components, passing props, setting state, and querying an API using useEffect(). Feeling confident in my understanding up to this point, I decided ...

Click on a designated button to choose a specific file on an HTML page

I need to be able to select a specific file by clicking on another button. A helpful solution that utilizes JavaScript to trigger the selection of a hidden file can be found in this answer. You can view the implementation here. In my scenario, I alre ...