What is the best way to assign a unique color to each circle?

Struggling to assign random colors to each circle in my canvas. Currently, they all have the same color that changes upon refresh.

I'm aiming for unique colors on each circle but my attempts have been unsuccessful so far.

Check out my code below:

var can = document.getElementById('canvas');
can.width = window.innerWidth;
can.height = window.innerHeight;

var ctx = can.getContext('2d');

function Circle(centerX, centerY, speedX, speedY, radius) {
  this.centerX = centerX;
  this.centerY = centerY;
  this.speedX = speedX;
  this.speedY = speedY;
  this.radius = radius;

  this.draw = function () {
    ctx.beginPath();
    ctx.arc(this.centerX, this.centerY, this.radius, 0, Math.PI * 2);
    ctx.fill();
  }

  this.update = function () {
    this.ctx.fillStyle = 
    this.centerX += this.speedX;
    if (this.centerX + this.radius > innerWidth || this.centerX - this.radius < 0) {
      this.speedX = -this.speedX;
    }

    this.centerY += this.speedY;
    if (this.centerY + this.radius > innerHeight || this.centerY - this.radius < 0) {
      this.speedY = -this.speedY;
    }
    this.draw();
  }
}

var circleArray = [];
var circleAmount = 45;

for (var i = 0; i < circleAmount; i++) {
  var centerX = Math.random() * window.innerWidth;
  var centerY = Math.random() * window.innerWidth;
  var radius = (Math.random() * 24) + 3;
  ctx.fillStyle = 'rgba(' + Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random() * 255) + ',' + ".5" + ')';     
  var speedY = (Math.random() - 0.5) * 3;
  var speedX = (Math.random() - 0.5) * 6;
  circleArray.push(new Circle(centerX, centerY, speedX, speedY, radius));
}

function draw() {
  requestAnimationFrame(draw);
  ctx.clearRect(0, 0, innerWidth, innerHeight);

  for(var i = 0; i < circleArray.length; i++){
    circleArray[i].update();
  }
}

draw();

Answer №1

Assign the color to the Circle constructor function and specify the fillColor in the update function:

var can = document.getElementById('canvas');
can.width = window.innerWidth;
can.height = window.innerHeight;

var ctx = can.getContext('2d');

function Circle(centerX, centerY, speedX, speedY, radius, color) {
  this.centerX = centerX;
  this.centerY = centerY;
  this.speedX = speedX;
  this.speedY = speedY;
  this.radius = radius;
  this.color = color;

  this.draw = function() {
    ctx.beginPath();
    ctx.fillStyle = this.color;
    ctx.arc(this.centerX, this.centerY, this.radius, 0, Math.PI * 2);
    ctx.fill();
  }

  this.update = function() {
    this.centerX += this.speedX;
    if (this.centerX + this.radius > innerWidth || this.centerX - this.radius < 0) {
      this.speedX = -this.speedX;
    }

    this.centerY += this.speedY;
    if (this.centerY + this.radius > innerHeight || this.centerY - this.radius < 0) {
      this.speedY = -this.speedY;
    }
    this.draw();
  }
}

var circleArray = [];
var circleAmount = 45;

for (var i = 0; i < circleAmount; i++) {
  var centerX = Math.random() * window.innerWidth;
  var centerY = Math.random() * window.innerWidth;
  var radius = (Math.random() * 24) + 3;
  var color = 'rgba(' + Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random() * 255) + ',' + ".5" + ')';

  var speedY = (Math.random() - 0.5) * 3;
  var speedX = (Math.random() - 0.5) * 6;
  circleArray.push(new Circle(centerX, centerY, speedX, speedY, radius, color));

}


function draw() {
  requestAnimationFrame(draw);

  ctx.clearRect(0, 0, innerWidth, innerHeight);

  for (var i = 0; i < circleArray.length; i++) {
    circleArray[i].update();
  }


}

draw();
<canvas id="canvas"></canvas>

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

Error encountered: SyntaxError - Missing semicolon before statement in AJAX call while processing JSON data

I am currently in the process of making a cross domain JSONP call utilizing this code snippet: jQuery.ajax({ async: true, url: 'http://mnews.hostoi.com/test.json', dataType: 'jsonp', method: "GET&quo ...

Troubleshooting issues with the IE flexible box model functionality

Working on incorporating the flexible box model into my website has been a bit challenging. It seems to function well in webkit-based browsers like Chrome and Safari, but I'm running into issues with Mozilla, Opera, and most notably Internet Explorer. ...

Removing other objects with Mongoose after an update

I'm facing an issue with my update query in mongoose. I can't figure out why other objects are getting deleted when I only intend to update one specific object. The code is functioning correctly in terms of updating, but it's causing all the ...

When viewed on a mobile device, the contact information bar should vertically collapse

Here is the code snippet I am working with: <div class="topbarsection"> <ul> <li class="alignleft"> <a href="#">Office Address</a> </li> <li class="aligncenter"> Office Timings ...

How about adjusting this RPG Battle Sequence?

Both the client and server sides of my game are built in JavaScript. I have opted not to implement a master game loop since combat is infrequent and nothing else in the game requires one. When two players engage in combat, they enter an auto-attack loop as ...

Limiting the style of an input element

How can I mask the input field within an <input type="text" /> tag to restrict the user to a specific format of [].[], with any number of characters allowed between the brackets? For example: "[Analysis].[Analysis]" or another instance: "[Analysi ...

What is the best method for deleting the div with id "__next" in Next.js?

I'm currently working on a website using Next.js and I'm aiming to create a header with a position: sticky; effect. Nevertheless, Next.js automatically inserts a div with the attribute id="__next" at the top of my website without my co ...

How can I position the arrows inside the Slick Slider instead of outside?

After discovering how user-friendly slick slider is, I decided to incorporate it into a website I have been developing: You can find the slider positioned at the bottom of the page. However, I am facing an issue where I would like the navigation arrows to ...

Problem of special characters not displaying properly in jQuery HTML code

I have encountered an issue with displaying special characters correctly. Despite my efforts, the characters are not showing up as intended. Here is how I defined it: var grade_value = 'Wešto izšamešđu'; Following that, I execute this code ...

What is the best way to contain the CSS for dynamically generated HTML within a div element without impacting other elements on the page?

I am currently facing a challenge where users can input any HTML into a text box, and I need to manipulate that HTML by identifying elements such as anchor tags or divs. To achieve this, I have created a hidden div and copied the pasted HTML into it using ...

I've recently delved into the world of JavaScript and am currently working on creating a calculator website. However, I'm facing some challenges in getting it to function

I created a calculator code using HTML, CSS, and JavaScript for a website. However, due to my limited experience with JavaScript coding, I encountered some issues. Currently, I have only implemented the number input part (not operations or deletion), but w ...

Content that moves with a flick of a finger

Seeking advice on a widely used JavaScript library that can facilitate scrolling for frequently updated content, similar to what popular websites like have implemented. I've had difficulty finding the right query on Google, so any recommendations or ...

Determine if the browser displays <select multiple> as a modal dialog

Is it possible to use JavaScript to detect whether a specific browser displays a focused <select multiple> element as a popup or strictly as an inline box? On certain platforms, like the Android Browser and iOS Safari, the appearance of a popup can ...

Tips for eliminating a worldwide ajax event handler using jQuery

Although it may not be the most advanced question (I am a beginner in JQuery), I am facing an issue: Whenever a specific button is clicked on my website, I must add a function that registers a global ajax event handler (.ajaxSend to be precise) and verifi ...

Customizing icons in jQuery alongside text: Tips and tricks

Here is the JsFiddle I'm currently working with: <div class="col-md-6"> <a id="IdAdvanceSearch" href="javascript:;" class="col-sm-offset-2" data-advance-search="S"> Show Advance Search <span class="glyphicon glyphi ...

JavaScript Array join() method returns an empty string

As a beginner in the world of javascript, I am just starting to dip my toes into it. In the past, I have used join() without any issues, but now I am facing a problem where this join is returning an empty string. Upon inspecting myArray, the data seems t ...

Can anyone assist with troubleshooting the font size issue for a JavaScript tooltip on Joomla 1.5 with CK Forms?

My Joomla 1.5 site has CK Forms installed and is functioning properly, except for one issue: the tooltip on the captcha is not displaying correctly. It appears in a tiny 1px font size. Even though I have tried debugging using Firebug and confirmed that the ...

Errors are caused when attempting to install third-party JS plugins using npm within a foundation project

I am currently exploring projects involving NodeJS and npm. While experimenting with foundation CLI in Foundation 6.4, I decided to install a 3rd Party JS plugin called chart.js from https://www.chartjs.org/ Following their documentation, I ran the comman ...

Enabling communication between my React frontend and Express server

I currently have a Digital Ocean Ubuntu VPS set up with Apache, Node, and Mongo running. I can successfully retrieve data from my database using CURL on the server and my node backend is running on port 3000. For my React frontend, I am using Fetch and it ...

In Vue using Typescript, how would I go about defining a local data property that utilizes a prop as its initial value?

When passing a prop to a child component in Vue, the documentation states: The parent component updates will refresh all props in the child component with the latest value. Avoid mutating a prop inside a child component as Vue will warn you in the consol ...