Reputation: 855
I'm trying to get hex code with in the 3 mixed colors based on values.
#FF0000
(Red).#FFFF00
(Yellow).#008000
(Green).If the value is:
1 - hex code is #FF0000
50 - hex code is #FFFF00
100 - hex code is #008000
In between values like, 1-50 the hex code should mixed with Red-Yellow.
50-100 hex code mixed with Yellow-Green based on value increasing.
How can i achieve this?
Upvotes: 2
Views: 2998
Reputation: 92327
Try
function change(e) {
box.style.background = gradient(e.target.value/100,'#FF0000','#FFFF00','#008000');
}
// t in ragne 0..1, start-middle-end are colors in hex e.g. #FF00FF
function gradient(t,start,middle,end) {
return t>=0.5 ? linear(middle,end,(t-.5)*2) : linear(start,middle,t*2);
}
function linear(s,e,x) {
let r = byteLinear(s[1]+s[2], e[1]+e[2], x);
let g = byteLinear(s[3]+s[4], e[3]+e[4], x);
let b = byteLinear(s[5]+s[6], e[5]+e[6], x);
return "#" + r + g + b;
}
// a,b are hex values from 00 to FF; x is real number in range 0..1
function byteLinear(a,b,x) {
let y = (('0x'+a)*(1-x) + ('0x'+b)*x)|0;
return y.toString(16).padStart(2,'0') // hex output
}
#box { width: 50px; height: 50px; background: #FF0000 }
<input type="range" min="0" max="100" oninput="change(event)" value="0">
<div id="box"></div>
Upvotes: 3