How can I calculate the average of three colors based on a given percentage?
For example we've green, yellow and red and want to get the average value:
The simplest way to do this is to create an image like this one:
And increase/decrease the background-position
:
$('input').change(function(){
$('#color').css({
backgroundPosition: -this.value + "px 0"
});
});
http://fiddle.jshell.net/VY4D8/
...however I think that can be done "better" with rgb/a
or hex
as output.
Just for interpretation purposes:
#ff0000
#ffc600
#ffee00
Is there already an implementation for this problem or has one of you written something in the past?
Update
Got it, thanks to Eevee https://stackoverflow.com/a/15125778/1250044:
var div = document.getElementsByTagName('div')[0];
$('input').change(function () {
var max = this.getAttribute("max"),
cur = this.value / max * max,
r = Math.min(cur * 2, max),
g = Math.min(max * 2 - cur * 2, max),
rgb = g + "%, " + r + "%, 0%";
div.style.backgroundColor = "rgb(" + rgb + ")";
}).change();
Do math?
You have:
rgb(100%, 0%, 0%)
rgb(100%, 100%, 0%)
rgb(0%, 100%, 0%)
If you want to figure out the color at 11%:
Figure out which section it belongs to. 11% of the full spectrum lies 22% of the way between red and yellow.
Interpolate: 22% of red plus 78% of yellow comes out to rgb(100%, 78%, 0%)
or #ffc600
.