From 99659adb9edd32fe2be8cc0215ce4c011c1baf94 Mon Sep 17 00:00:00 2001 From: Rob Watson Date: Fri, 12 Nov 2021 13:36:03 +0100 Subject: [PATCH] Basic error handling when reading peaks --- frontend/src/WaveformCanvas.tsx | 80 +++++++++++++++++---------------- 1 file changed, 42 insertions(+), 38 deletions(-) diff --git a/frontend/src/WaveformCanvas.tsx b/frontend/src/WaveformCanvas.tsx index ee46fde..675753c 100644 --- a/frontend/src/WaveformCanvas.tsx +++ b/frontend/src/WaveformCanvas.tsx @@ -26,45 +26,49 @@ export const WaveformCanvas: React.FC = (props: Props) => { const canvasRef = useRef(null); useEffect(() => { - const canvas = canvasRef.current; - if (canvas == null) { - console.error('no canvas ref available'); - return; - } - - const ctx = canvas.getContext('2d'); - if (ctx == null) { - console.error('no 2d context available'); - return; - } - - ctx.strokeStyle = props.strokeStyle; - ctx.fillStyle = props.fillStyle; - ctx.fillRect(0, 0, canvas.width, canvas.height); - - if (props.peaks == null) { - return; - } - - const chanHeight = canvas.height / props.channels; - - let frameIndex = 0; - props.peaks.forEach((peaks) => { - for (let chanIndex = 0; chanIndex < peaks.length; chanIndex++) { - const yOffset = chanHeight * chanIndex; - const val = peaks[chanIndex]; - const height = Math.floor((val / maxPeakValue) * chanHeight); - const y1 = (chanHeight - height) / 2 + yOffset; - const y2 = y1 + height; - ctx.beginPath(); - ctx.globalAlpha = props.alpha; - ctx.moveTo(frameIndex, y1); - ctx.lineTo(frameIndex, y2); - ctx.stroke(); - ctx.globalAlpha = 1; + (async function () { + const canvas = canvasRef.current; + if (canvas == null) { + console.error('no canvas ref available'); + return; } - frameIndex++; - }); + + const ctx = canvas.getContext('2d'); + if (ctx == null) { + console.error('no 2d context available'); + return; + } + + ctx.strokeStyle = props.strokeStyle; + ctx.fillStyle = props.fillStyle; + ctx.fillRect(0, 0, canvas.width, canvas.height); + + if (props.peaks == null) { + return; + } + + const chanHeight = canvas.height / props.channels; + + let frameIndex = 0; + await props.peaks + .forEach((peaks) => { + for (let chanIndex = 0; chanIndex < peaks.length; chanIndex++) { + const yOffset = chanHeight * chanIndex; + const val = peaks[chanIndex]; + const height = Math.floor((val / maxPeakValue) * chanHeight); + const y1 = (chanHeight - height) / 2 + yOffset; + const y2 = y1 + height; + ctx.beginPath(); + ctx.globalAlpha = props.alpha; + ctx.moveTo(frameIndex, y1); + ctx.lineTo(frameIndex, y2); + ctx.stroke(); + ctx.globalAlpha = 1; + } + frameIndex++; + }) + .catch(console.error); + })(); }, [props.peaks]); const canvasStyles = {