embroidery-viewer/src/lib/utils/shadeColor.js
2025-06-04 15:31:53 -03:00

27 lines
837 B
JavaScript

/**
* Shades a hex color by a given percentage.
* Positive values lighten the color, negative values darken it.
*
* @param {string} color - A 7-character hex color string (e.g. "#ffcc00").
* @param {number} percent - A percentage from -100 to 100 to adjust brightness.
* @returns {string} - The adjusted hex color string.
*/
function shadeColor(color, percent) {
const num = parseInt(color.slice(1), 16);
const amt = Math.round(2.55 * percent);
let r = (num >> 16) + amt;
let g = ((num >> 8) & 0xff) + amt;
let b = (num & 0xff) + amt;
// Clamp each component between 0 and 255
r = Math.min(255, Math.max(0, r));
g = Math.min(255, Math.max(0, g));
b = Math.min(255, Math.max(0, b));
const shaded = (1 << 24) + (r << 16) + (g << 8) + b;
return `#${shaded.toString(16).slice(1)}`;
}
export { shadeColor };