Skip to content

Instantly share code, notes, and snippets.

@frontend-sensei
Created February 10, 2024 11:55
Show Gist options
  • Save frontend-sensei/d41ed57ff2e3b4c48f742d77bb937aa5 to your computer and use it in GitHub Desktop.
Save frontend-sensei/d41ed57ff2e3b4c48f742d77bb937aa5 to your computer and use it in GitHub Desktop.
Convert SVG colors to Black and white
function convertColorsToTotalBlackAndWhite(svgString) {
const BLACK_THRESHOLD = 128;
const WHITE_THRESHOLD = 127;
const convertColor = (color) => {
if (color.toLowerCase() === 'none') {
return color; // Leave "none" unchanged
}
const hexToDecimal = (hex) => parseInt(hex, 16);
const [r, g, b] = [1, 3, 5].map((start) => hexToDecimal(color.substr(start, 2)));
const brightness = (r * 299 + g * 587 + b * 114) / 1000;
if (brightness >= BLACK_THRESHOLD) {
return '#ffffff'; // Convert to total white
} else {
return '#000000'; // Convert to total black
}
};
const updatedSvg = svgString.replace(/fill=["']([^"']+)["']/g, (match, color) => {
const newColor = convertColor(color);
return `fill="${newColor}"`;
});
return updatedSvg;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment