From 5b59f8569855d6ddfd9cab1f98b470d4e2811610 Mon Sep 17 00:00:00 2001 From: ying_123 Date: Thu, 18 Jan 2024 12:41:59 +0800 Subject: [PATCH] add color fallback --- package.json | 2 +- src/lib/index.tsx | 23 ++++++++++++++--------- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index 86f61e2..c7c10fb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "react-audio-visual", - "version": "1.0.6", + "version": "1.0.7", "description": "a react audio visual component", "main": "index.js", "types": "index.d.ts", diff --git a/src/lib/index.tsx b/src/lib/index.tsx index 9bcaac0..8d17163 100644 --- a/src/lib/index.tsx +++ b/src/lib/index.tsx @@ -59,18 +59,22 @@ function AudioVisual({ const canvas = useRef(null) const drawCanvas = (buffer: Uint8Array) => { - const interval = width / Math.floor(width / (barInternal * dpr)); - const gapWidth = barSpace * dpr; - const ctx = canvas.current!.getContext('2d')!; - const gradient = ctx.createLinearGradient(width / 2, 0, width / 2, height); - for (let i = 0; i < colors.length; i++) { - gradient.addColorStop(i / (colors.length - 1), colors[i]); + const interval = width / Math.floor(width / (barInternal * dpr)) + const gapWidth = barSpace * dpr + const ctx = canvas.current!.getContext('2d')! + if (colors.length > 1) { + const gradient = ctx.createLinearGradient(width / 2, 0, width / 2, height) + for (let i = 0; i < colors.length; i++) { + gradient.addColorStop(i / (colors.length - 1), colors[i]) + } + ctx.fillStyle = gradient + } + else { + ctx.fillStyle = colors[0] ?? '#fff' } - ctx.clearRect(0, 0, width, height); - ctx.fillStyle = gradient; const step = Math.floor( interval * fftSize / width - ); + ) const steps = Math.floor(fftSize / step); if (!caps.current || caps.current && caps.current.length !== steps) { caps.current = Array.from({ length: steps }, _ => 0) @@ -80,6 +84,7 @@ function AudioVisual({ v => v > 0 ? v - 1 : v ) } + ctx.clearRect(0, 0, width, height) for (let i = 0; i < steps; i++) { const intensity = Math.round( buffer.slice(i, i + step).reduce(