From 5dd5f49d69f6209e19ff2d87aa5d906ef9fdf4fd Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Fri, 25 Sep 2026 11:48:43 +0200 Subject: [PATCH] chore: rgba parser from hex added to color util --- src/utils/color.ts | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/utils/color.ts b/src/utils/color.ts index 37e73dd8..1db42981 100644 --- a/src/utils/color.ts +++ b/src/utils/color.ts @@ -29,3 +29,27 @@ export function convertHexToRGBA(color: string): number { const alphaChannel = 0xff; return (colorValue << 8) | alphaChannel; } + +/** + * Parses any valid CSS color string into its RGB components, + * using the canvas's own color parser for correctness across + * hex (#fff, #ffffff), rgb()/rgba(), hsl(), and named colors. + */ +export function parseColorToRgb(color: string): { + r: number; + g: number; + b: number; +} { + const canvas = document.createElement('canvas'); + canvas.width = canvas.height = 1; + const ctx = canvas.getContext('2d'); + if (!ctx) { + throw new Error('Canvas context not supported'); + } + + ctx.fillStyle = color; // browser validates & normalizes the color here + ctx.fillRect(0, 0, 1, 1); + + const [r, g, b] = ctx.getImageData(0, 0, 1, 1).data; + return { r, g, b }; +}