ユーザーアイコン

mizuko

3か月前

0
0

Chart.jsで利用する円グラフの色を自動生成する

Next.js
Chart.js

baseColorを元に、同系色で徐々に色を変化する様にしている。

export const generateBackgroundColors = ( baseColor: string, count: number ): string[] => { const colors: string[] = []; for (let i = 0; i < count; i++) { const hsl = hexToHsl(baseColor); const saturation = hsl.s + i * (50 / count); // 彩度を徐々に増やす const lightness = hsl.l + i * (35 / count); // 輝度を徐々に上げる const color = `hsl(${hsl.h}, ${saturation}%, ${lightness}%)`; colors.push(color); } return colors; }; // 16進数のカラーコードをHSL表現に変換する関数 const hexToHsl = (hex: string): { h: number; s: number; l: number } => { const r = parseInt(hex.substring(1, 3), 16) / 255; const g = parseInt(hex.substring(3, 5), 16) / 255; const b = parseInt(hex.substring(5, 7), 16) / 255; const max = Math.max(r, g, b); const min = Math.min(r, g, b); let h = 0; let s = 0; const l = (max + min) / 2; if (max === min) { h = s = 0; // achromatic } 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; } h /= 6; } return { h: Math.round(h * 360), s: Math.round(s * 100), l: Math.round(l * 100), }; };