Tips for continuously randomizing colors in p5.js

I recently began exploring p5.js and I have a query regarding color randomization. Currently, it seems that the color only changes randomly when I restart the code. Is there a way to trigger this randomization every time the mouse is clicked?

Below is the code snippet I am working with:

let r, g, b; 

function setup() {
  createCanvas(400, 400);
  r = random(255);
  g = random(255);
  b = random(255);
}

function draw() {
  if (mouseIsPressed) {
    fill(r,g,b);
  } else {
    fill(255);
  }
  ellipse(mouseX, mouseY, 80, 80);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>

Answer №1

To change the color values of r, g, and b when the mouse is clicked, follow these steps:

let r = 255, g = 255, b = 255; 

function setup() {
    createCanvas(400, 400);
}

function mousePressed() {
    r = random(255);
    g = random(255);
    b = random(255);
}

function draw() {
    fill(r, g, b);
    ellipse(mouseX, mouseY, 80, 80);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>

Answer №2

It is true that Rabbid76 suggests overwriting the r, g, b variables to persist their values after releasing the mouse. However, it is recommended to perform this action within the mousePressed global function to prevent multiple triggers from occurring.

let red;
let green;
let blue;

function setup() {
  createCanvas(400, 400);
  randomizeColors();
}

function draw() {
  fill(red, green, blue);
  ellipse(mouseX, mouseY, 80, 80);
}

function mousePressed() {
  randomizeColors();
}

function randomizeColors() {
  red = random(255);
  green = random(255);
  blue = random(255);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.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

Angular 6: Simplify Your Navigation with Step Navigation

Can someone please assist me with configuring a navigation step? I tried using viewchild without success and also attempted to create a function with an index++ for three components on the same page. However, I am unable to achieve the desired outcome. Any ...

Create proper spacing for string formatting within an AngularJS modal

I am working with a popup that displays output as one string with spaces and newline characters. Each line is concatenated to the previous line, allowing for individual adjustments. Test1 : Success : 200 Test2 : Su ...

Redirecting asynchronously in Node.js with no use of AJAX

I've been struggling with this issue for days and have already sought help, but nothing seems to be working. Whenever I attempt to redirect from a POST request in node, the browser doesn't respond. Here's how my app is structured: ./ confi ...

The functionality of uploading files in Dropzone.js is not supported on Windows operating systems

I am currently working on a file uploader using dropzone functionality. I will share the code with you shortly, but first let me outline the problem: My setup consists of an Ubuntu machine running the server code in node.js using the multer library. The f ...

How can I ensure a successful redirect to react-router root path after saving to MongoDB in Express?

As a newcomer to React and react-router, I may be making some rookie mistakes in my project. Currently, I am constructing a web application with React and react-router as the frontend server, paired with Express and MongoDB for the backend. To communicate ...

Tips for Developing Drag Attribute Directive in Angular 2.0

Currently, I am referencing the Angular documentation to create an attribute directive for drag functionality. However, it seems that the ondrag event is not functioning as expected. Interestingly, the mouseenter and mouseleave events are working fine ac ...

React Native's fetch function appears to be non-responsive

I am experiencing an issue where the fetch function does not seem to fire in my React Native component: import { Button } from 'react-native'; export function Test() { function submit() { console.log('submit'); fetch('h ...

Guide for displaying retrieved information on a Bootstrap Modal window following data submission in Yii2

I'm encountering an issue with a Modal popup that contains two fields. The first field is used to submit information and perform an internal database query, while the second field should display the returned data. Oddly enough, when testing the functi ...

The tab indicator in Material-UI fails to update when the back button is clicked

My code is currently functioning well: The tab indicator moves according to the URL of my tab. However, there is a peculiar issue that arises when the back button of the browser is pressed - the URL changes but the indicator remains on the same tab as befo ...

What is the best way to create a new row at a specific index in an ng-repeat loop?

My Goal: I am aiming to insert a new row of ul after every 2 elements in my ng-repeat loop. For example: <ul class="col-sm-2"> <li><p>Automobile & Motorcycle</p></li> ...

Looking to deactivate a particular checkbox in a chosen mode while expanding the tree branches

I encountered an issue with a checkbox tree view where I needed to disable the first two checkboxes in selected mode. While I was able to achieve this using the checked and readonly properties, I found that I could still uncheck the checkboxes, which is no ...

What is the method for placing a title in the initial column with the help of v-simple-table from Vuetify.js?

I am interested in using the v-simple-table UI component from Vuetify.js to create a table similar to the one shown below. After creating the code in codesandbox and previewing the output, I noticed that the title is not aligned properly. HTML↓ < ...

What is the best way to send the selected option from a dropdown to a button click function within the controller?

I need to pass the selected value from a user's country selection dropdown to the ng-click="saveChanges()" function on the submit button. Is there a correct method for achieving this? I want to be able to access the user's selection from the dro ...

Easy Div Centering with jQuery Toggle for Internet Explorer 6

Press the button to center the div, press it again to align it to the left. This feature is compatible with all browsers except for IE6, which does not support margin: 0 auto;. How can I find a solution to this issue? The width of the div is not fixed and ...

Show a mpld3 graph in an HTML page using the Django framework

Incorporating mpld3 to showcase matplotlib charts within an HTML page through django has been my recent focus. I utilize the mpld3.fig_to_dict method to convert a matplotlib figure into a JSON string and store it in a variable. However, I am encountering ...

Issue with clicking a button in Selenium using JavaScript for automation

I'm encountering an issue where Selenium is detecting an element as disabled, despite it being enabled. To work around this, I am attempting to click on the element using JavaScript with the following code snippet: IWebElement button = driver.FindEl ...

ReactJs Error: Unable to access property value because it is undefined (trying to read '0')

I am currently attempting to retrieve and display the key-value pairs in payload from my JSON data. If the key exists in the array countTargetOptions, I want to show it in a component. However, I am encountering an error message stating Uncaught TypeError ...

Error in compiled.php on line 7772: Laravel throwing a RuntimeException when sending HTTP requests from Angular

Hey there, I've been encountering an error intermittently while using Angular $http methods with a Laravel API. Can someone please explain what this error means and suggest potential solutions? I've shared the error log on CodePen for easier refe ...

Tips for loading a unique class name on the initial active UI react component

Is there a way to load a class named "Landingpage" to the body tag or main container div only when the first tab/section (Overview page) is active? The tab sections are located in a child component. Any assistance would be appreciated. Click here for more ...

Experiencing a missing handlebars helper error when utilizing a helper within partials in express-handlebars

I have set up custom helpers using express-handlebars like this: const { create } = require("express-handlebars"); // Configuring the handlebars engine const hbs = create({ helpers: require("./config/handlebars-helpers"), }); app.engi ...