From eefd883e651b4ce761d004b7929ee0e404fbfccf Mon Sep 17 00:00:00 2001 From: William Entriken Date: Mon, 30 Sep 2024 16:30:12 -0400 Subject: [PATCH 1/3] Support CSS colors --- src/confetti.js | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/src/confetti.js b/src/confetti.js index 8fdbea2..867b447 100644 --- a/src/confetti.js +++ b/src/confetti.js @@ -281,18 +281,11 @@ return colors.map(hexToRgb); } - function hexToRgb(str) { - var val = String(str).replace(/[^0-9a-f]/gi, ''); - - if (val.length < 6) { - val = val[0]+val[0]+val[1]+val[1]+val[2]+val[2]; - } - - return { - r: toDecimal(val.substring(0,2)), - g: toDecimal(val.substring(2,4)), - b: toDecimal(val.substring(4,6)) - }; + function hexToRgb(color) { + const ctx = document.createElement("canvas").getContext("2d"); + ctx.fillStyle = color; // Set the fill style to the input color + const [r, g, b] = ctx.fillStyle.match(/\w\w/g).map(hex => parseInt(hex, 16)); // Convert to RGB + return { r, g, b }; } function getOrigin(options) { From f402c61710035cfe4e31eac7b2eedfa68cee78b1 Mon Sep 17 00:00:00 2001 From: William Entriken Date: Sun, 8 Dec 2024 00:40:28 -0500 Subject: [PATCH 2/3] Update src/confetti.js Co-authored-by: lionel-rowe --- src/confetti.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/confetti.js b/src/confetti.js index 867b447..c628908 100644 --- a/src/confetti.js +++ b/src/confetti.js @@ -278,7 +278,7 @@ } function colorsToRgb(colors) { - return colors.map(hexToRgb); + return colors.map(colorToRgb); } function hexToRgb(color) { From ca405a7fa95f0d42d68e967475fde82d230b4c2d Mon Sep 17 00:00:00 2001 From: William Entriken Date: Sun, 8 Dec 2024 00:41:01 -0500 Subject: [PATCH 3/3] Update src/confetti.js Co-authored-by: lionel-rowe --- src/confetti.js | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/confetti.js b/src/confetti.js index c628908..d78c2c4 100644 --- a/src/confetti.js +++ b/src/confetti.js @@ -281,11 +281,20 @@ return colors.map(colorToRgb); } - function hexToRgb(color) { - const ctx = document.createElement("canvas").getContext("2d"); - ctx.fillStyle = color; // Set the fill style to the input color - const [r, g, b] = ctx.fillStyle.match(/\w\w/g).map(hex => parseInt(hex, 16)); // Convert to RGB - return { r, g, b }; + var canvas = typeof OffscreenCanvas === 'function' ? new OffscreenCanvas(0, 0) : document.createElement('canvas'); + var ctx = canvas.getContext('2d'); + var colorCache = Object.create(null); + + function colorToRgb(color) { + if (colorCache[color] != null) return colorCache[color]; + + ctx.fillStyle = color; + var match = ctx.fillStyle.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i); + + if (match == null) throw new Error('Unsupported color value: ' + color); + + var rgb = match.slice(1).map(function(hex) { return parseInt(hex, 16); }); + return colorCache[color] = { r: rgb[0], g: rgb[1], b: rgb[2] }; } function getOrigin(options) {