Search code examples
javascriptjqueryjquery-calculation

Calculate the average from 3 colors based on a percentage


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:

enter image description here

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:

  • ** [0%] | #ff0000
  • -- [1%]
  • -- [2%]
  • -- [3%]
  • -- [4%]
  • -- [5%]
  • -- [...]
  • ** [11%] | #ffc600
  • -- [12%]
  • -- [13%]
  • -- [14%]
  • -- [15%]
  • -- [16%]
  • ** [17%] | #ffee00
  • ...etc...

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();

http://fiddle.jshell.net/VY4D8/1/


Solution

  • Do math?

    You have:

    • at 0%, red: rgb(100%, 0%, 0%)
    • at 50%, yellow: rgb(100%, 100%, 0%)
    • at 100%, green: rgb(0%, 100%, 0%)

    If you want to figure out the color at 11%:

    1. Figure out which section it belongs to. 11% of the full spectrum lies 22% of the way between red and yellow.

    2. Interpolate: 22% of red plus 78% of yellow comes out to rgb(100%, 78%, 0%) or #ffc600.