Search code examples
javascriptcolorsrgba

Combine RGB color values in JavaScript to form a blend


So, in JavaScript, if I have a percentage of red and green right, say 35% red, 65% green, how can I combine them? I am not completely sure on the terminology of this, and it is possible that it is simpler than I think. I see that on http://www.rapidtables.com/web/color/RGB_Color.htm they have a value that ranges from 0-255. Is it easy to assign a value from 0-255 for both red and green to mix? If it is not incredibly different, does adding alpha to the mix work too?

I want the color to be able show up in a canvas, but once I have the mixed value this should work fine. So I need a legitimate value that I can put into fillStyle.

var c=document.getElementById("myCanvas");
ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.fillStyle="the blended color";
ctx.fill();

Solution

  • RGB (Red, Green, Blue) have indeed values from 0-255 for each color. So I assume that converting the percentage in a value within that range should work fine?

    As you perform the following code for each color you can combine all values to get an RGB value.

    color = (percentage / 100.00) * 255.00
    

    Example snippet

    function percentageToRGB(r,g,b) {
        var r = parseInt((r/100)*255);
        var g = parseInt((g/100)*255);
        var b = parseInt((b/100)*255);
        
        return "rgb("+ r +","+ g +","+ b +")";
    }
    
    document.getElementById("block").style.background = percentageToRGB(35, 65, 0);
    #block {
        width: 200px;
        height: 100px;
        text-align: center;
        border: 1px solid black;
        line-height: 100px;
    }
    <div id="block">
        Hello
    </div>