Create a spectrum of vibrant colors depending on the numerical value

I'm attempting to create a function that generates rainbow colors based on a numerical value.

var max = 10000;
var min = 0;
var val = 8890;

function getColor(min, max, val) {
     // code to return color between red and black
 }

Possible Colors: Red Yellow Green Blue Black (when value is 0)

Check out the example at https://i.sstatic.net/MRevs.jpg

Given the values provided, how can we generate a color ranging from red to black, with high values corresponding to red and low values to black?

Answer №1

If you want to achieve this task, there are a few key things you should keep in mind. The RGB colorspace might not be the best choice for what you're trying to do - it's recommended to use either HSV or HSL instead. Since most browsers support HSL, let's go with that option.

Take a look at the H channel of the HSL colorspace and you'll find the exact range of colors you need. Blue typically has a hue of around 240° while red is closer to 0­°.

To achieve our goal, we need to map the range of [min..max] to the hues of [240..0] (it may seem backwards but it works). Let's create a function that will handle this mapping and provide us with a valid color string.

function calcColor(min, max, val)
{
    var minHue = 240, maxHue=0;
    var curPercent = (val - min) / (max-min);
    var colString = "hsl(" + ((curPercent * (maxHue-minHue) ) + minHue) + ",100%,50%)";
    return colString;
}

We establish the two Hues end-points we want to work with first. Then, determine where the current value falls within the range. Finally, translate that position to the corresponding Hue range rather than keeping it in the user-input range.

An example demonstrating its usage is provided below.

<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function newEl(tag){return document.createElement(tag);}

window.addEventListener('load', onDocLoaded, false);

function onDocLoaded()
{
    for (var i=0; i<10; i++)
    {
        var elem = newEl('div');
        elem.style.backgroundColor = calcColor(0, 9, i);
        elem.className = "rgb";
        document.body.appendChild(elem);
    }
}

function calcColor(min, max, val)
{
    var minHue = 240, maxHue=0;
    var curPercent = (val - min) / (max-min);
    var colString = "hsl(" + ((curPercent * (maxHue-minHue) ) + minHue) + ",100%,50%)";
    return colString;
}

</script>
<style>
.rgb
{
    width: 16px;
    height: 16px;
    display: inline-block;
}
</style>
</head>
<body>
</body>
</html>

Answer №2

Here's how to create color gradients:

If you have a range of values from min to max and want to transition colors from black to red, divide the range into 6 phases:

First phase: Start with RGB values of (0, 0, 0) at the lower end and (0, 0, 255) at the higher end for a gradient from black to blue.

Second phase: Transition from (0, 0, 255) to (0, 255, 0) for a gradient from blue to green.

Third phase: Change from (0, 255, 0) to (255, 255, 0) to achieve yellow.

Fourth phase: Shift from (255, 255, 0) to (255, 0, 0) to reach red.

Calculate intermediate values using proportions.

Enjoy :), here's a code example for further clarification...

https://jsfiddle.net/4cq8fqjg/10/

Answer №3

Give this a try.

Utilize the following library. https://github.com/bgrins/TinyColor

Determine the percentage of your input relative to the maximum value.

Execute the script using the calculated percentage.

tinycolor("hsv (_CALCULATED PERCENTAGE_ 100% 100%)");

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

Click on the link to see the jQuery effect in action

I'm trying to achieve a fade-out effect on the current page followed by fading in a new one. The fade-in effect is working fine, but when I click on the link, the new page loads without first fading out the existing content. The div that I want to app ...

Is there a way to retrieve two arrays in an Ajax request?

JAVASCRIPT CODE: $.ajax({ url: 'assignavailtrainers.php', data: {action:'test'}, type: 'post', success: function(data) { } }); PHP CODE: <?php $username = "trainerapp"; ...

Installing a specific version of yarn on Ubuntu

Is there a way to install yarn version 0.27.5 in Ubuntu despite the fact that the latest update is for version 1.2.1? ...

What is the process for embedding a 3D model using three.js into a specific div on a webpage?

Lately, I've been struggling with a persistent issue. I can't seem to figure out how to integrate my three.js scene into a div on my website. Despite watching numerous YouTube videos and reading countless articles on the topic, I still haven&apos ...

Node.js POST request only executes successfully on the second attempt

I am facing a peculiar issue where upon submitting a form, it redirects to the form action URL and then displays a blank page. However, upon reloading the page, the data is displayed. index.jade - http://172.18.0.60:3000/ form#command(action='runc ...

What causes the error message 'avoid pushing route with duplicate key' when using NavigationStateUtils in React Native?

Within my React Native + Redux project, I have set up a reducer for navigation utilizing NavigationStateUtils: import { PUSH_ROUTE, POP_ROUTE } from '../Constants/ActionTypes' import { NavigationExperimental } from 'react-native' impo ...

Modifying the CSS class of an element does not produce the desired effect after altering its styles using JavaScript

html: <input id="myinput" class="cinput" type="image" src="http://www.foodwater.org.au/images/triple-spiral-3-small-button.jpg"/> <br><br><br><br> <button id="s">set to visible class</button> <button id="h"> ...

Opening the media library in Wordpress through the Angular JS function triggered by an ng-click event

I have been working on a plugin where I need to select an image from the media library. However, despite having implemented the code correctly to call the media library window, I encounter an issue. When I click the button to select an image, nothing happe ...

Creating an event declaration using Javascript's onclick function

As I was getting ready to add an onclick event to my element in JavaScript, a question popped into my mind regarding the efficiency of these two options: document.getElementById(myid).onclick = function(e){...} or document.body.onclick = fun ...

When using JSON.stringify, the output is null. However, when using document.write, the data

I am currently working on a plugin for crawljax that involves executing some JavaScript code, similar to the following: String result = browser.executeJavaScript(script).toString(); The script code is as follows: function getElementPosition(id) { var el ...

What is the mechanism for invoking functions defined with the arrow syntax in Angular?

Referencing this code snippet from the tutorial at https://angular.io/tutorial/toh-pt4, specifically within the hero.component.ts file: getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } After analyz ...

Issuing a straightforward GET request results in a significant delay in receiving a response

I have a simple app running on Node.js, Handlebars, and Express. The main page features a single button that triggers an asynchronous GET request when clicked, causing a console.log message to display. Initially, the first click on the Submit button shows ...

Display a list exclusively with radio button options

Currently, I am developing a module that allows the admin to view a list of candidates who have requested approval. The interface includes radio buttons for three different selections and a submit button. However, I would like to update this functionality ...

Transform the JSON object into a different JSON format

I am in the process of restructuring the JSON data which is currently organized by categories, with each category containing multiple locations. Each location consists of latitude/longitude coordinates and an area code: { "cat1":[ {"location":{ ...

What is the best way to utilize two values in Vue.js 2?

When I attempt to structure my component in the following way: <script> export default { template: '\ <select class="form-control" v-on:change="search">\ <option v-for="option in option ...

Scrapy Library's Response.css function fails to retrieve data from API, resulting in an empty list

scrapy shell 'https://www.samsung.com/in/smartphones/galaxy-m/' fetch('https://searchapi.samsung.com/v6/front/b2c/product/finder/gpv2?type=01010000&siteCode=in&start=1&num=12&sort=onlineavailability&onlyFilterInfoYN=N& ...

Enhance the functionality of your React app by making the `<Paper>` component in Material UI clickable

I'm trying to figure out how to make a Paper component clickable. I attempted to set an id property in the tag like () and then utilize the DOM to add an event listener, but it's not working. I've hit a roadblock and I'm running out of ...

Is it possible to modify the appearance of the element that was just clicked on?

Hello everyone, I'm currently working on a form with different inputs, all with the same class: <input type="text" name="username" class="field" /> <input type="text" name="email" class="field" /> I'm trying to figure out how to ch ...

Could you please explain the distinctions among onLoad, onDomready, No wrap - in <head>, and No wrap - in <body>?

When it comes to editing my code, I rely on JSFiddle. However, I have noticed that in certain instances when running JavaScript or jQuery, the code only works if I choose "No wrap - <head>" or "No wrap - <body>". CLICK HERE FOR THE JSFIDDLE EX ...

A custom script developed to detect the presence of the numeric combination "11" and promptly notify the

I am attempting to develop a unique chrome extension that detects typing errors in orders. For example, if the user accidentally types "11" instead of "1", an alert should be triggered. However, I am encountering an issue where the script is running in an ...