UNPKG

mt-music-player

Version:

A simply web music player app.

123 lines (105 loc) 2.9 kB
export function randomColor(type) { const randomNumber = () => Math.floor(Math.random() * 256); const color = [randomNumber(), randomNumber(), randomNumber()]; if (type === 'hex') { return `#${color.reduce((p, c) => p + c.toString(16), '')}`; } return [randomNumber(), randomNumber(), randomNumber()]; } export function luminance(r, g, b) { const a = [r, g, b].map((v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; }); return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722; } export function contrast(rgb1, rgb2) { const l1 = luminance(rgb1[0], rgb1[1], rgb1[2]) + 0.05; const l2 = luminance(rgb2[0], rgb2[1], rgb2[2]) + 0.05; return Math.max(l1, l2) / Math.min(l1, l2); } /** * Converts an RGB color value to HSL. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes r, g, and b are contained in the set [0, 255] and * returns h, s, and l in the set [0, 1]. * * @param Number r The red color value * @param Number g The green color value * @param Number b The blue color value * @return Array The HSL representation */ export function rgbToHsl(r, g, b) { r /= 255; g /= 255; b /= 255; const max = Math.max(r, g, b); const min = Math.min(r, g, b); let h; let s; const l = (max + min) / 2; if (max === min) { // achromatic h = 0; s = 0; } else { const d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; default: } h /= 6; } return [h, s, l]; } export function hueToRGB(p, q, t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1 / 6) return p + (q - p) * 6 * t; if (t < 1 / 2) return q; if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; } /** * Converts an HSL color value to RGB. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes h, s, and l are contained in the set [0, 1] and * returns r, g, and b in the set [0, 255]. * * @param Number h The hue * @param Number s The saturation * @param Number l The lightness * @return Array The RGB representation */ export function hslToRGB(h, s, l) { let r; let g; let b; if (s === 0) { // achromatic r = l; g = l; b = l; } else { const q = l < 0.5 ? l * (1 + s) : l + s - l * s; const p = 2 * l - q; r = hueToRGB(p, q, h + 1 / 3); g = hueToRGB(p, q, h); b = hueToRGB(p, q, h - 1 / 3); } return [r * 255, g * 255, b * 255]; } export const hexToRGB = str => str .replace('#', '') .split(/(\w{2})?/) .filter(e => e) .map(e => Number(`0x${e}`));