Domanda

I am using a linear gradient background image to paint a DIV background.

background-image: linear-gradient(to bottom,  #cdeb8f 0%,#a5c955 100%); 

Linear gradient looks good better than a simple background color. Is it possible to create this kind of linear gradients by javascript for a given HEX color?

I mean I want to pass a HEX color value to a function as parameter and it should return me a lighter or darker HEX color so that I can create the above good looking gradient.

Given as above, if I pass

#cdeb8f 

it should return me

#a5c955

I converted above HEX values into Decimals and found that they have a 1.24 ratio. I then used a function to convert passed HEX into Decimal, multiplying or dividing it by 1.24 and convert back to HEX. Return HEX color did not create a meaningful linear gradient with the passed HEX color.

The main problem is to keep the above proportion so that the linear gradient does not look weird.

È stato utile?

Soluzione

You can start from here. You can also pass the ratio as a parameter.

Hex and RGB conversion functions taken from Tim's answer.

var div = document.getElementById("div");
var hex = "#cdeb8f";

gradient(hex, div);

function gradient(topColor, elm) {
    function hexToRgb(hex) {
        var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
        hex = hex.replace(shorthandRegex, function(m, r, g, b) {
            return r + r + g + g + b + b;
        });

        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    }

    function componentToHex(c) {
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    }

    function rgbToHex(r, g, b) {
        return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
    }

    var ratio = 1.24;
    var top = hexToRgb(topColor);
    var r = Math.floor(top.r / ratio);
    var g = Math.floor(top.g / ratio);
    var b = Math.floor(top.b / ratio);
    var bottom = rgbToHex(r, g, b);
    var bg = "linear-gradient(to bottom,  " + hex + " 0%, " + bottom + " 100%)";
    elm.style.background = bg;
}

FIDDLE

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top