Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to produce a smooth color range from two colors in JS [duplicate]

I have two color pickers (start, end) and I need to produce a color range from start to end. The problem I have is the stepping from one to the next. If it was just green I could go from 0-255 on the G channel but being I have 3 channels(rgb) it's rather confusing.

My first thought was to convert rrggbb (hex) to dec and just add to the result. I could then convert it back to RGB This gives me a nice rang in short bursts. For example I get a nice light yellow to dark yellow but after that it goes to blue.

var val = Number( this.gridIDMap.cellAt( j, i ).innerHTML );
val = Math.floor( val );
var r = 256 - Math.floor( val / ( 256 * 256 ) );
var g = 256 - Math.floor( val / 256 ) % 256;
var b = 256 - Math.floor( val % 256 );
this.gridIDMap.cellAt( j, i ).style.backgroundColor = "rgba(" + r + "," + g + "," + b + ",.25)";

So I'm guessing I could do this with hue saturation but not sure how to do so. Ideally it would be grate to go from blue to red and get a blue to purple to red effect. I'm sure that is possible but it may require a 3rd party include. I have not found anything that does this so far. I don't have to use decimal the color picker has a few options (RGB, hsl, and hex). https://github.com/PitPik/tinyColorPicker

like image 971
Sean Green Avatar asked Jan 01 '26 01:01

Sean Green


1 Answers

If you wanted a function to give you a range(array) of colors between two colors, here's another option at JSFiddle

Here's the main code for it:

var GColor = function(r,g,b) {
    r = (typeof r === 'undefined')?0:r;
    g = (typeof g === 'undefined')?0:g;
    b = (typeof b === 'undefined')?0:b;
    return {r:r, g:g, b:b};
};
var createColorRange = function(c1, c2) {
    var colorList = [], tmpColor;
    for (var i=0; i<255; i++) {
        tmpColor = new GColor();
        tmpColor.r = c1.r + ((i*(c2.r-c1.r))/255);
        tmpColor.g = c1.g + ((i*(c2.g-c1.g))/255);
        tmpColor.b = c1.b + ((i*(c2.b-c1.b))/255);
        colorList.push(tmpColor);
    }
    return colorList;
};
like image 157
Micaiah Wallace Avatar answered Jan 03 '26 15:01

Micaiah Wallace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!