Generate a random color using Javascript on every page load

Using JavaScript, I am dynamically creating a graph based on a Bootstrap template.

This particular graph displays various appointment types and their corresponding values.

try {
    //bar chart
    var ctx = document.getElementById("ReferralTypeWeekly");
    if (ctx) {
      ctx.height = 200;
      var myChart = new Chart(ctx, {
        type: 'bar',
        defaultFontFamily: 'Poppins',
        data: {
          labels: ["Apt Type 1", "Apt Type 2", "Apt Type 3", "Apt Type 4", "Apt Type 5", "Apt Type 6", "Apt Type 7", "Apt Type 8", "Apt Type 9", "Apt Type 10", "Apt Type 11"],
          datasets: [
            {
              label: "Week 06",
              data: [7, 31, 47, 41, 10, 42, 3, 19, 16, 24, 0, 26],
              borderColor: "rgba(0, 123, 255, 0.9)",
              borderWidth: "0",
              backgroundColor: "rgba(0, 123, 255, 0.5)",
              fontFamily: "Poppins"
            },
            {
              label: "Week 07",
              data: [10, 67, 112, 57, 21, 39, 9, 23, 30, 26, 9, 54],
              borderColor: "rgba(0,0,0,0.09)",
              borderWidth: "0",
              backgroundColor: "rgba(123, 255, 0,0.5)",
              fontFamily: "Poppins"
            },
            {
              label: "Week 08",
              data: [4, 47, 93, 58, 21, 29, 6, 10, 32, 30, 6, 33],
              borderColor: "rgba(0,0,0,0.09)",
              borderWidth: "0",
              backgroundColor: "rgba(255, 0, 123,0.5)",
              fontFamily: "Poppins"
            }
          ]
        },
        options: {
          legend: {
            position: 'top',
            labels: {
              fontFamily: 'Poppins'
            }

          },
          scales: {
            xAxes: [{
              ticks: {
                fontFamily: "Poppins"

              }
            }],
            yAxes: [{
              ticks: {
                beginAtZero: true,
                fontFamily: "Poppins"
              }
            }]
          }
        }
      });
    }


  } catch (error) {
    console.log(error);
  }

In the code snippet where it references:

borderColor: "rgba(0, 123, 255, 0.9)",

and

backgroundColor: "rgba(0, 123, 255, 0.5)",

I wish to generate these colors randomly from a predefined list, ensuring each set has a unique color but maintains consistency between borderColor and backgroundColor for each value.

Despite researching, I am unsure how to implement this feature.

Some of my other graphs involve multiple datasets (more than just two like in this example).

I eagerly await any suggestions on how to proceed.

Cheers!

UPDATE : CHECK OUT THIS IMAGE OF THE GRAPH https://i.sstatic.net/jeKyz.png

Answer №1

If you're looking to generate random colors from a predefined list, you can use the `splice` method on the array at a random index:

var predefinedList = ["0,0,0", "255,255,255", "255,0,0", "0,255,0", "128,128,128", "0,128,0"];

function getRandomColor() {
  return predefinedList.splice(Math.floor(Math.random() * predefinedList.length), 1)[0];
}

document.querySelector("#test").addEventListener("click", function() {
  console.log(getRandomColor());
});

To add more random values and create up to 256 unique colors in the `predefinedList`, you can follow this approach:

var start = Date.now();

function fillArray(size, callBack) {
  return Array.apply(null, Array(size)).map(callBack);
}

function getIndex(val, index) {
  return index;
}

var r = fillArray(256, getIndex);
var g = fillArray(256, getIndex);
var b = fillArray(256, getIndex);

var predefinedList = fillArray(256, function() {
  return [r, g, b].map(function(color) {
    return color.splice(Math.floor(Math.random() * color.length), 1)[0];
  }).join(",");
});

console.log("Milliseconds elapsed: " + (Date.now() - start));

console.log(predefinedList);

You can combine both methods to get an array of randomized RGB colors:

function fillArray(size, callBack) {
  return Array.apply(null, Array(size)).map(callBack);
}

function getIndex(val, index) {
  return index;
}

var r = fillArray(256, getIndex);
var g = fillArray(256, getIndex);
var b = fillArray(256, getIndex);

var predefinedList = fillArray(256, function() {
  return `rgb(${[r, g, b].map(function(color) {
    return color.splice(Math.floor(Math.random() * color.length), 1)[0];
  }).join(",")})`;
});


function getRandomColor() {
  return predefinedList.splice(Math.floor(Math.random() * predefinedList.length), 1)[0];
}

var container = document.querySelector("#container");
var color = getRandomColor();

while (color){
  var newDiv = document.createElement("div");
  newDiv.setAttribute("style", `background-color: ${color};`);
  container.appendChild(newDiv);
  color = getRandomColor();
} 

In addition, you can create arrays for `r`, `g`, and `b` with custom indexing functions like this:

function fillArray(size, callBack) {
  return Array.apply(null, Array(size)).map(callBack);
}

function createIndexFunction(start, multiplier) {
  return function(val, index) {
    return start + index * multiplier;
  }
}

var r = fillArray(26, createIndexFunction(0, 10));
var g = fillArray(26, createIndexFunction(200, 1));
var b = fillArray(26, createIndexFunction(50, 5));

console.log(r);
console.log(g);
console.log(b);

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 utilizing MUI's ThemeProvider, it may result in encountering errors that display as "undefined"

I am facing an issue with my MUI application. Everything was working perfectly until I decided to implement a ThemeProvider. It seems that as soon as I add the ThemeProvider, the application breaks and all MUI components I'm using start throwing undef ...

Is there a way to obtain the "rotated" coordinates of a mouse click within a canvas element?

Exploring New Features Within my image editing software, there is a canvas where users can draw shapes. These shapes are sent to a server and added to an XML file, which is then returned to the client for display. Now, I am looking to enhance the program ...

Do not apply tailwindcss styles to Material-UI

I've been struggling to apply styling from tailwindcss to my MUI button. My setup includes babel and webpack, with the npm run dev script as "webpack --mode development --watch". tailwind.css module.exports = { content: ["./src/**/*.{js, jsx, t ...

Refresh the information displayed in the open Google Maps Infowindow

Experimenting with extracting JSON data from a bus tracker website and integrating it into my own version using Google Maps. Although not as visually appealing, I'm struggling to update an infowindow while it remains open. Despite finding some example ...

Checking for null properties in Typescript objectsorHow to verify if a

What is a simple way to determine if the properties of an object in TypeScript are nullable? For example export default interface UserDto{ ID?:int; USER_NAME?:string; FIRST_NAME?:string; LAST_NAME?:string; USER_ROLE?: ...

What is the most effective method for incorporating web APIs (such as setTimeout, fetch, etc.) within the V8 engine?

Currently, I am tackling a project that requires the use of v8 in Go for running JS code. To achieve this, I am utilizing the v8Go library. The challenge I am facing is the inability to utilize functionalities like fetch, setTimeout, and other Web APIs. Wh ...

How can I load only specific images on a webpage using HTML?

I attempted to implement an image filter for my website by using the code below: <script> function myFunction() { // Initialize variables var input, filter, ul, li, a, i; input = document.getElementById('myInput'); filter = input.value.toU ...

Providing properties to the main Vue.js components

An Issue I'm Facing I am currently attempting to pass a prop to my root constructor. To achieve this, I have been exploring the use of propsData, which I learned about from this resource: var appComponent = Vue.component('app', require(&ap ...

To link the information within the angularJS controller

I've recently generated a div element dynamically within the controller function of my AngularJS application. However, I'm facing an issue where the data is not binding as expected inside this div element. Here is a snippet of my code: function ...

Tips for ensuring all my onclick event are clickable in iOS browser

Currently, I am developing a web page using HTML5 and JQuery Mobile. I have encountered an issue where the onclick function does not work on iOS device browsers. Is there a way to change all onclick events to be accessible through tapping instead? This wou ...

What is the best way to extract the data from an object received in an AJAX GET request?

I am fetching a variable object type from an Ajax get request and my goal is to access the values within a table row in that object. $.get(url2, function (responseGET) { var responseGETHtml2 = $(responseGET).find(".data-item-form form.form" ...

Establishing a TCP connection to a server using Javascript

Currently, I have developed a server daemon that generates various data, such as messages. However, my main focus is on client monitoring. For instance, I have a webpage and I aim to maintain a constant TCP connection to the server in order to display all ...

How can I retrieve a list of downloads utilizing the Chrome.downloads api?

I have developed an extension that needs to display all the downloads from the user's downloads folder on a webpage instead of opening the download folder directly. Below is the code I have implemented: window.onload = function(){ var maxNumOfEn ...

"Twice the loading of Meteor templates: once with an undefined collection, and once with it

After searching various resources for solutions to my issue, I stumbled upon this helpful and . Both of these links provided valuable insights. The issue I'm facing is that one of my templates is loading twice - first with the collection undefined, ...

Load the content of the dialog and transfer variables

After struggling for days, I am still unable to find a solution to my current dilemma. In my database, there are approximately 1300 items each with its own unique "id", a corresponding "name", and a property called "enabled". My goal is to display links t ...

Use an external javascript file in AngularJS if permitted

To ensure that my HTML page only loads an external JavaScript file when the variable $scope.jsallowed is set to true, I attempted the following code implementation within my AngularJS based page: <script src="assets/js/slider.min.js" data-ng-if="jsallo ...

The inconsistency in hydration of children in <div> is due to the server-rendered element having a different number of child nodes than the client-side Virtual

Why is the hydration of children mismatched in this server-rendered element, containing fewer child nodes than the client VDOM? Nuxt Link not working when used within Slick carousel I'm experiencing duplicate content without Slick carousel and I&apo ...

Wordpress API returned an error with the code "rest_invalid_json" and the message "Invalid JSON data provided."

I'm struggling to figure out where I went wrong in my code. Could someone please offer some insight into what might be causing the error I'm encountering? Below is the code snippet I'm working with. I can confirm that the route is being succ ...

Experiencing issues launching the server.js file on Node.js while incorporating socket.io

Several months ago, I was able to successfully run this code without any issues. However, recently I have encountered some unexpected problems. This code is for a whiteboard app that can be viewed on this link. The current issue I am facing is that when ...

Customers will refresh themselves whenever the supplier refreshes

After reading through the React documentation, it explains that re-rendering all consumers occurs each time the Provider is re-rendered due to a new object being created for value. To see this in action, I decided to create a simple example: class App ...