Search code examples
javascriptcolorshsl

Color gradiant beween red, white and green in javascript


I am trying to create a function like this:


function colorCell(current, min=-100, max=100) {
    current = Math.max(min, Math.min(current, max));

    return 'hsl(' + ((max + current) * 135 / (max - min)) + ", 100%, 50%)";
}

If current = 0, color should be white. If current is between 0 and min, color should move from light red to dark red. If color <= min, it should return same dark red.

Then it repeats the same thing between 0 and max but green color gradiant here.


Solution

  • I created this function to solve my problem

    function colorCell(current, min = -100, max = 100) {
        current = Math.max(min, Math.min(current, max));
    
        if (current < 0) {
            var percent = (1 - current / min) * 100;
            return `hwb(0deg ${percent}% 0%)`;
        }
        if (current > 0) {
            var percent = (1 - current / max) * 100;
            return `hwb(135deg ${percent}% 0%)`;
        }
    }