Skip to content

Instantly share code, notes, and snippets.

@NeilPandya
Created September 21, 2024 18:41
Show Gist options
  • Save NeilPandya/d1a81b35c4267ea90487de99b0b7e87c to your computer and use it in GitHub Desktop.
Save NeilPandya/d1a81b35c4267ea90487de99b0b7e87c to your computer and use it in GitHub Desktop.
Generate a Rainbow in HTML
<!--
"I am trying to generate rainbow colors based on the numeric value."
var max = 10000;
var min = 0;
var val = 8890;
function getcolor(min,max,val) {
// return red - black;
}
colors Red Yellow Green Blue Black (value == 0)
"From the above values how to generate color between red - black. High value is red and low value is black."
There's just a couple things you need to do and understand in order to accomplish this task. The first is realizing that the RGB colourspace is not the one you want for this task - the HSV or HSL ones are far better. Since the browsers are happy to work with HSL, we'll use that one.
Next, if you look at the H channel of the HSL colourspace, you can see that the exact band of colours you want is present there. The blue has a hue of about 240° and the red has one of 0­°.
This means that we want to map the range of [min..max] to the Hues of [240..0] (yes, the mapping is 'backwards') With this in mind, we can set about creating a function that will do the mapping for us and return a valid colour 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;
}
First, we setup the two end-points of the Hues that we wish to use. Next, we work out where abouts in the current range the current value is. Finally, we put ourselves in the same position relatively speaking, in the Hue range instead of the user-input range.
A simple, example of its use is shown.
-->
<!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(1, 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment