Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Native JavaScript to Desaturate a Colour

I have a colour picker where the user can specify a hex colour.

I also want a saturation slider where the user can adjust the saturation, and get the new hex colour as an output.

Is there a way I can, in JavaScript, convert a saturation value, and a hex colour, into a new hex colour?

So, say for example I have a value #FF0000 and a saturation of 50 (out of 100) how would I ascertain the new hex colour from this?

I can't use any libraries for it because I'm creating it as a plugin for my website, and I'm trying to keep it as light as possible.

like image 288
Dan Hanly Avatar asked Nov 12 '12 17:11

Dan Hanly


1 Answers

http://jsfiddle.net/5sfDQ/

$("#color, #saturation").change(function(){
    updateColor();
});

function updateColor(){
    var col = hexToRgb($("#color").val());
    var sat = Number($('#saturation').val())/100;
    var gray = col.r * 0.3086 + col.g * 0.6094 + col.b * 0.0820;

    col.r = Math.round(col.r * sat + gray * (1-sat));
    col.g = Math.round(col.g * sat + gray * (1-sat));
    col.b = Math.round(col.b * sat + gray * (1-sat));

    var out = rgbToHex(col.r,col.g,col.b);

    $('#output').val(out);

    $('body').css("background",out);
}

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

function hexToRgb(hex) {
    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;
}
like image 163
Shmiddty Avatar answered Oct 10 '22 14:10

Shmiddty