getSvgFillColor function
Reads the fill color of an SVG element as rendered, whatever sets it: attribute, class, inherited style.
ts
import { getSvgFillColor } from 'utils';Signature
ts
export function getSvgFillColor(element: SVGGraphicsElement): RgbParameters
| Name | Description |
|---|---|
element | A rendered SVG element. |
Returns
The fill color.
Errors
- Throws TypeError: When the fill is not an sRGB color, such as
noneor a gradient.
Example
ts
getSvgFillColor(tank); // { r: 0, g: 128, b: 255 }Tests
Line coverage: 100 %.
- ✅ reads rgb(0, 128, 255)
- ✅ reads rgba(10, 20, 30, 0.5)
- ✅ reads rgb(10 20 30)
- ✅ throws a TypeError for none
- ✅ throws a TypeError for url("#gradient")
Source
src/color/get-svg-fill-color.ts (on GitHub)
Uses
Rgb: An sRGB color, each channel from 0 to 255.
Files it needs
src/color/get-svg-fill-color.ts imports, directly or not:
Source code
ts
import type { Rgb } from './rgb';
const RGB_PATTERN = /^rgba?\((?<r>[\d.]+)[,\s]+(?<g>[\d.]+)[,\s]+(?<b>[\d.]+)/v;
/**
* Reads the fill color of an SVG element as rendered, whatever sets it: attribute, class, inherited style.
*
* @param element - A rendered SVG element.
* @returns The fill color.
* @throws {TypeError} When the fill is not an sRGB color, such as `none` or a gradient.
* @example
* getSvgFillColor(tank); // { r: 0, g: 128, b: 255 }
*/
export function getSvgFillColor(element: SVGGraphicsElement): Rgb {
const { fill } = getComputedStyle(element);
const groups = RGB_PATTERN.exec(fill)?.groups;
if (!groups) {
throw new TypeError(`The fill is not an sRGB color: '${fill}'`);
}
return { r: Number(groups['r']), g: Number(groups['g']), b: Number(groups['b']) };
}Test file
ts
import { getSvgFillColor } from './get-svg-fill-color';
describe(getSvgFillColor, () => {
const element = {} as SVGGraphicsElement;
afterEach(() => {
vi.unstubAllGlobals();
});
it.for([
['rgb(0, 128, 255)', { r: 0, g: 128, b: 255 }],
['rgba(10, 20, 30, 0.5)', { r: 10, g: 20, b: 30 }],
['rgb(10 20 30)', { r: 10, g: 20, b: 30 }],
] as const)('reads %s', ([fill, expected]) => {
vi.stubGlobal('getComputedStyle', () => ({ fill }));
expect(getSvgFillColor(element)).toStrictEqual(expected);
});
it.for(['none', 'url("#gradient")'])('throws a TypeError for %s', (fill) => {
vi.stubGlobal('getComputedStyle', () => ({ fill }));
expect(() => getSvgFillColor(element)).toThrow(TypeError);
});
});Keywords: get, svg, fill, color, colors, function