This is old but, in May 2024, I got it to work by creating conversion functions. Ol does not accept rgba(...), but rgb(...) is fine and you can still include the opacity.
- hexToRgb takes two arguments: hex, opacity
- Because we want to use rgb values, we assume the current style's color is already rgb, so in rgbToHex, convert rgb to hex using the first three values(removes opacity).
- Convert the hex to rgb and embed new opacity.
export const hexToRgb = (hex: string, opacity: number): string => {
let r = '0', g = '0', b = '0';
if (hex.length === 4) {
r = hex[1] + hex[1];
g = hex[2] + hex[2];
b = hex[3] + hex[3];
}
if (hex.length === 7) {
r = hex[1] + hex[2];
g = hex[3] + hex[4];
b = hex[5] + hex[6];
}
return `rgb(${parseInt(r, 16)}, ${parseInt(g, 16)}, ${parseInt(b, 16)}, ${opacity})`;
}
export const rgbToHex = (rgb: string): string => {
let [r, g, b, _a] = rgb.split(',').map((color) => parseInt(color));
return `#${r.toString(16)}${g.toString(16)}${b.toString(16)}`;
}
Below is how I used it in a React component that allows the user to style features on the fly.
const handleChange = (_e: any) => {
let color = _e.target?.value || `#FFFFFF`;
let newStyles = props.styles;
// @ts-ignore
newStyles[mode]['circle-fill-color'] = hexToRgb(color, props.styles[mode]['fill-opacity'])
setStyles(newStyles);
};