Disabling dynamic color updates upon refresh

I am currently using chartjs and I want to generate new random colors each time the page is refreshed. However, I need these colors to remain fixed and not change after a page refresh or reload. Below is the function I am working with:

getRandomRgb() {
    var num = Math.round(0xffffff * Math.random());
 
    var r = num >> 16;
    var g = (num >> 8) & 255;
    var b = num & 255;
    return "rgb(" + r + ", " + g + ", " + b + ")";
  }

This is where I implemented the function:

this.currentResponseItems.forEach((x) => {
            x.Items.forEach((z) => {
              if (!colorMap[z.Description]) {
                colorMap[z.Description] = this.getRandomColor();
              }
              console.log(z.Description, " : ", colorMap[z.Description]);
              z["phaseId"] = x.Id;
              let zData = [];

              let number = array.indexOf(z.phaseId);
              if (z.Number != 0) {
                zData[number] = z.Number;

                this.barChartData.push({
                  data: zData,
                  stack: x.Id,
                  label: z.Description,
                  fill: false,
                  grouped: true,
                  idStatoAffiliazione: x.Id,
                  channelID: z.Id,
                  backgroundColor: colorMap[z.Description],
                  hoverBackgroundColor: colorMap[z.Description],
                  pointBackgroundColor: colorMap[z.Description],
                  pointBorderColor:colorMap[z.Description],
                  pointHoverBackgroundColor:colorMap[z.Description],
                  pointHoverBorderColor: colorMap[z.Description],
                
                }); 

Below is the HTML code for the chartjs:

 <div class="container-chart cursor-pointer" fxLayout="row" *ngIf="barChartData.length > 0" fxLayoutGap="20px">
                <canvas baseChart fxFlex="100" [chartType]="'horizontalBar'" [datasets]="barChartData" [options]="barChartOptions" [labels]="barChartLabels" [colors]="graphColors" ></canvas>
                <!-- <graph-legend fxFlex="20" [configs]="graphLegendConfig"></graph-legend> -->
            </div>

Answer №1

Assuming you have an array named colorMap containing all the colors, it is recommended to store this array in localStorage. However, before saving it, make sure to stringify it. Update your if statement as follows:

// Store in local storage after generating the array
localStorage.setItem("colorMap", JSON.stringify(colorMap));

Your conditional should appear like this:

// Check if colors are saved in localStorage
if(!localStorage.getItem("colorMap")){
  // Generate new random values
} else { 
  // Retrieve the stored array from local storage
  colorMap = JSON.parse(localStorage.getItem("colorMap"));
}

Answer №2

To maintain the color even after a page reload without utilizing a server, you will need to save it in the user's browser. One method is storing it using localStorage. Here is an example of how your function could be implemented:

function getStoredRgb(colorIdentifier) {
    if (localStorage.hasOwnProperty(`storedRgb-${colorIdentifier}`)) return localStorage.getItem(`storedRgb-${colorIdentifier}`)

    var num = Math.round(0xffffff * Math.random());
    var red = num >> 16;
    var green = (num >> 8) & 255;
    var blue = num & 255;
    var storedRgbValue = "rgb(" + red + ", " + green + ", " + blue + ")";

    localStorage.setItem(`storedRgb-${colorIdentifier}`, storedRgbValue)
    return storedRgbValue
}

In your scenario, to generate a color for a specific colorIdentifier, you can use:

getStoredRgb(colorDictionary[z.Name])

Alternatively, you could store the entire color dictionary in localStorage instead of individual colors.

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

Is there a way to stabilize a section or content that bounces as I scroll?

Whenever I scroll up or down, there is a section on my page where I have implemented scroll magic. However, as I scroll through this section, it starts to jump until it reaches the position where I want it to be with transform:translateY(0). I am unsure h ...

Enhance Compatibility: IE11 URL Polyfill

While creating a URL in my angular app using new URL, I have encountered an issue that it works on all browsers except IE11. To resolve this problem, I attempted to add "url-polyfill" to my "package.json" and imported 'url-polyfill' in the polyf ...

Understanding the relationship between csv and json array formats, along with the process of converting them into a json array using Node.js

Greetings! I have been searching for quite some time and have not been able to find the desired result. I am unsure of what a CSV file would look like with the following JSON array: [ { email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email_ ...

Encountering an issue with a class component stating that "this.setState is not a function

I am currently learning React JS and encountered an error when calling my first API in React. I keep getting the message "Unhandled Rejection (TypeError): this.setState is not a function." I have been trying to troubleshoot this issue on my own but haven ...

Transfer information from a single form and distribute it across multiple forms with the help of jQuery or Javascript

Form1 has a variety of input fields including text, select, radio, and textarea. At the bottom there is a button labeled "copy" that allows users to copy data from all the fields in Form1. In different pages, I have three to four other forms with input fi ...

Error loading GLTF file

I'm having trouble displaying a GLTF model using three.js. If someone could help me identify the issue in my code, I would greatly appreciate it. import {GLTFLoader} from "./GLTFLoader.js"; var scene = new THREE.Scene(); ...

Is it possible to rearrange the slide order in Swiper Grid View?

<swiper-container class="mySwiper" slides-per-view="3" grid-rows="2" grid-fill="row" [navigation]="false" space-between="30"> <swiper-slide *ngFor="let item of lists;"& ...

Issue with Material UI grid not rendering properly in TypeScript environment

I've been trying to replicate a grid from material-ui using React and Typescript. You can see a live demo here. I modified the example to work with Typescript, so my demo.tsx file looks like this: Code goes here... If you check out the live demo, y ...

What causes the "The requested URL could not be retrieved" error to appear when using an angular app?

I'm in the process of running an Angular app. Once I successfully completed the npm install, I proceeded to run npm start. The outcome is as follows: https://i.stack.imgur.com/JpSP0.png However, I encountered the following error when attempting to op ...

Discover the best correlation among multiple arrays

I am currently developing a chat script that allows users to specify their interests. Upon connecting to the server, the client sends a JSON payload over WebSocket containing information such as ID, hash, auto message, and interests. {"id": int, "hash": m ...

Combining existing CSS classes with node labels in Cytoscape JS for Angular: A Guide

My project follows a consistent CSS theme, but the node's CSS style doesn't match. I'm looking to adjust the label colors in the CSS based on whether it's day mode or night mode. How can I accomplish this? this.cy = cytoscape({ con ...

When utilizing the Angular library in an Ionic project, make sure to call the inject() function within an injection context

I have been working on a project that involves an angular workspace containing an angular web app and an angular ionic app. In an effort to reuse my existing authentication service, which utilizes AngularFireauth and AngularFirestore, I extracted the servi ...

Issue with HTML5 Video Play on Hover Functionality Ceases to Work Upon Loading Dynamic Content

I recently implemented a feature on my WordPress site that allows videos to start playing when the mouse hovers over their thumbnails and pause when it leaves. However, I encountered an issue where this function works perfectly upon initial page load but f ...

Enhance Your Text Areas with Vue.js Filtering

Currently, I am working with a textarea that has v-model: <textarea v-model="text"></textarea> I am wondering how to filter this textarea in Vue. My goal is to prevent the inclusion of these HTML quotes: &amp;amp;#039;id&amp;amp;#039 ...

The performance of the Ajax Jquery remove function leaves something to be desired

My table has items with a delete button for each row. To achieve this, I created the following Ajax function: $(document).ready(function() { $(".destroy-device").click(function(e) { e.preventDefault(); var id = $(this).attr("data-id"); $.aj ...

Creating a worldwide directive using AngularJS

I'm currently working on implementing a directive that will manage user interaction with the navigation system on my website. The directive includes an element.click event listener in the link function, which is responsible for toggling the display of ...

Quill editor streamlining excess whitespace

Is there a way to prevent PrimeNG Quill's p-editor in angular from trimming extra space by default? For example, if the model binding property is set to text = " Hi I am Angular", the output in the editor would be "Hi I am Angular". However, the exp ...

Combining React with a jQuery plugin

Utilizing the jQuery nestable plugin in my React App has been a lifesaver for meeting my business needs. Despite being aware of the potential complications that arise from mixing jQuery with React, I couldn't find the exact functionality I required in ...

Spin the text inside an <li> element generated by JavaScript

I am currently working on a unique script designed to create a custom number of slices for a circle. The items in the circle are being displayed as shown in this generated circle image. This is the Javascript code I have been using: for () { men ...

Gatsby, in combination with TSC, does not properly transpile the rest operator

I'm attempting to integrate TypeScript with Gatsby following the guidelines provided here. However, I am encountering an issue where the tsc command is failing to transpile the spread (...) operator and producing the error shown below: WAIT Compili ...