Created
November 20, 2023 03:13
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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