function zeroPad(num, totalDigits) {
let padding = '0';
num = num + '';
while (num.length < totalDigits) {
num = padding + num;
}
return num;
};
// Adjust the color based on a ratio between 0 and 1
function adjustColor(color, ratio, darker) {
// Remove any leading/trailing whitespace
color = color.replace(/^\s*|\s*$/, '');
// Expand short hex codes to full six-digit format
color = color.replace(
/^#?([a-f0-9])([a-f0-9])([a-f0-9])$/i,
'#$1$1$2$2$3$3'
);
// Calculate the difference for adjusting the color
var value = Math.round(ratio * 256) * (darker ? -1 : 1),
// Check if the input is in RGB(A) format
rgbValues = color.match(new RegExp('^rgba?\\(\\s*' +
'(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])' +
'\\s*,\\s*' +
'(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])' +
'\\s*,\\s*' +
'(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])' +
'(?:\\s*,\\s*' +
'(0|1|0?\\.\\d+))?' +
'\\s*\\)$'
, 'i')),
alphaValue = !!rgbValues && rgbValues[4] != null ? rgbValues[4] : null,
// Convert hex to decimal
decimalValue = !!rgbValues ? [rgbValues[1], rgbValues[2], rgbValues[3]] : color.replace(
/^#?([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])/i,
function() {
return parseInt(arguments[1], 16) + ',' +
parseInt(arguments[2], 16) + ',' +
parseInt(arguments[3], 16);
}
).split(/,/),
result;
// Return the adjusted RGB(A) or hex color
return !!rgbValues ?
'rgb' + (alphaValue !== null ? 'a' : '') + '(' +
Math[darker ? 'max' : 'min'](
parseInt(decimalValue[0], 10) + value, darker ? 0 : 255
) + ', ' +
Math[darker ? 'max' : 'min'](
parseInt(decimalValue[1], 10) + value, darker ? 0 : 255
) + ', ' +
Math[darker ? 'max' : 'min'](
parseInt(decimalValue[2], 10) + value, darker ? 0 : 255
) +
(alphaValue !== null ? ', ' + alphaValue : '') +
')' :
// Get the adjusted hex color
[
'#',
zeroPad(Math[darker ? 'max' : 'min'](
parseInt(decimalValue[0], 10) + value, darker ? 0 : 255
).toString(16), 2),
zeroPad(Math[darker ? 'max' : 'min'](
parseInt(decimalValue[1], 10) + value, darker ? 0 : 255
).toString(16), 2),
zeroPad(Math[darker ? 'max' : 'min'](
parseInt(decimalValue[2], 10) + value, darker ? 0 : 255
).toString(16), 2)
].join('');
};
function makeLighter(color, ratio) {
return adjustColor(color, ratio, false);
};
function makeDarker(color, ratio) {
return adjustColor(color, ratio, true);
};
// Example usage
var darkened = makeDarker('rgba(80, 75, 52, .5)', .2);
var lightened = makeLighter('rgba(80, 75, 52, .5)', .2);
This updated version now supports both RGB(A) and hex input formats (short and long).