45 lines
1.1 KiB
TypeScript
45 lines
1.1 KiB
TypeScript
|
|
import type { TimelineState } from './renderer';
|
||
|
|
|
||
|
|
export function drawWaveform(
|
||
|
|
ctx: CanvasRenderingContext2D,
|
||
|
|
state: TimelineState,
|
||
|
|
peaks: number[],
|
||
|
|
duration: number,
|
||
|
|
y: number,
|
||
|
|
height: number
|
||
|
|
): void {
|
||
|
|
if (peaks.length === 0 || duration <= 0) return;
|
||
|
|
|
||
|
|
const { width, visibleStart, visibleEnd } = state;
|
||
|
|
const visibleRange = visibleEnd - visibleStart;
|
||
|
|
|
||
|
|
ctx.fillStyle = '#89b4fa44';
|
||
|
|
ctx.strokeStyle = '#89b4fa88';
|
||
|
|
ctx.lineWidth = 1;
|
||
|
|
|
||
|
|
ctx.beginPath();
|
||
|
|
ctx.moveTo(0, y + height);
|
||
|
|
|
||
|
|
for (let px = 0; px < width; px++) {
|
||
|
|
const startSample = Math.floor(
|
||
|
|
((visibleStart + ((px - 0.5) / width) * visibleRange) / duration) * peaks.length
|
||
|
|
);
|
||
|
|
const endSample = Math.floor(
|
||
|
|
((visibleStart + ((px + 0.5) / width) * visibleRange) / duration) * peaks.length
|
||
|
|
);
|
||
|
|
|
||
|
|
let maxPeak = 0;
|
||
|
|
for (let i = Math.max(0, startSample); i <= Math.min(endSample, peaks.length - 1); i++) {
|
||
|
|
maxPeak = Math.max(maxPeak, peaks[i]);
|
||
|
|
}
|
||
|
|
|
||
|
|
const barHeight = maxPeak * height;
|
||
|
|
ctx.lineTo(px, y + height - barHeight);
|
||
|
|
}
|
||
|
|
|
||
|
|
ctx.lineTo(width, y + height);
|
||
|
|
ctx.closePath();
|
||
|
|
ctx.fill();
|
||
|
|
ctx.stroke();
|
||
|
|
}
|