Skip to content

Instantly share code, notes, and snippets.

@AshKyd
Created November 20, 2023 03:13
Show Gist options
  • Save AshKyd/c1b42db0ede1402a13aa9a1bfbf1a6ff to your computer and use it in GitHub Desktop.
Save AshKyd/c1b42db0ede1402a13aa9a1bfbf1a6ff to your computer and use it in GitHub Desktop.
Convert any HTML colour to its rgb equivalent using HTML5 canvas. Suitable for use in a web worker using OffscreenCanvas.
const colourToRgbaMemo = {};
/**
* Parse and convert HTML colours to RGB representations.
* @param {string} sourceColour - Any valid HTML colour. E.g. ('#ff0000', 'rgba(128,128,255)' or 'hotpink')
* @returns {number[]} RGB triplet representing the given colour. If the colour was invalid, returns black.
*/
export function colourToRgb(sourceColour) {
// return from cache if available
if (colourToRgbaMemo[sourceColour]) return colourToRgbaMemo[sourceColour];
// HTML5 canvas converts HTML colours and lets us read them back without drawing.
const canvas = typeof OffscreenCanvas === 'undefined' ? document.createElement('canvas') : new OffscreenCanvas(1, 1);
const ctx = canvas.getContext('2d');
ctx.fillStyle = sourceColour;
// split hex components and convert them to decimal
const hexComponents = ctx.fillStyle.match(/^#(..)(..)(..)$/)?.slice(1) || ['0', '0', '0'];
const decimalComponents = hexComponents.map(component => parseInt(component, 16));
// cache and return
colourToRgbaMemo[sourceColour] = Object.freeze(decimalComponents);
return decimalComponents;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment