UNPKG

@tsparticles/plugin-hex-color

Version:

tsParticles hex color plugin

39 lines (38 loc) 1.54 kB
var RgbIndexes; (function (RgbIndexes) { RgbIndexes[RgbIndexes["r"] = 1] = "r"; RgbIndexes[RgbIndexes["g"] = 2] = "g"; RgbIndexes[RgbIndexes["b"] = 3] = "b"; RgbIndexes[RgbIndexes["a"] = 4] = "a"; })(RgbIndexes || (RgbIndexes = {})); const shorthandHexRegex = /^#?([a-f\d])([a-f\d])([a-f\d])([a-f\d])?$/i, hexRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i, hexRadix = 16, defaultAlpha = 1, alphaFactor = 0xff; export class HexColorManager { accepts(input) { return input.startsWith("#"); } handleColor(color) { return this.#parseString(color.value); } handleRangeColor(color) { return this.#parseString(color.value); } parseString(input) { return this.#parseString(input); } #parseString(hexColor) { if (typeof hexColor !== "string" || !this.accepts(hexColor)) { return; } const hexFixed = hexColor.replace(shorthandHexRegex, (_, r, g, b, a) => { return r + r + g + g + b + b + (a === undefined ? "" : a + a); }), result = hexRegex.exec(hexFixed); return result ? { a: result[RgbIndexes.a] ? Number.parseInt(result[RgbIndexes.a], hexRadix) / alphaFactor : defaultAlpha, b: Number.parseInt(result[RgbIndexes.b] ?? "0", hexRadix), g: Number.parseInt(result[RgbIndexes.g] ?? "0", hexRadix), r: Number.parseInt(result[RgbIndexes.r] ?? "0", hexRadix), } : undefined; } }