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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With