Basic error handling when reading peaks

This commit is contained in:
Rob Watson 2021-11-12 13:36:03 +01:00
parent 97db31209c
commit 99659adb9e
1 changed files with 42 additions and 38 deletions

View File

@ -26,45 +26,49 @@ export const WaveformCanvas: React.FC<Props> = (props: Props) => {
const canvasRef = useRef<HTMLCanvasElement>(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 = {