Files
dsp-thomann-interface/src/features/dsp408/utils/graph/draw.ts
T

108 lines
2.7 KiB
TypeScript

import { CHANNEL_COLORS } from '../../constants';
import { CurvePoint, CurveStyle, Curve, DEFAULT_CURVE_COLORS, sumCurvePoints } from './curve';
export { sumCurvePoints };
type ToPx = (x: number, y: number) => [number, number];
type CanvasCtx = CanvasRenderingContext2D;
const DEFAULT_STYLE: Required<Omit<CurveStyle, never>> = {
strokeColor: DEFAULT_CURVE_COLORS.strokeColor,
fillColors: DEFAULT_CURVE_COLORS,
fill: true,
lineWidth: 2,
dimmed: false,
};
function drawSingleCurve(
ctx: CanvasCtx,
toPx: ToPx,
points: CurvePoint[],
xMin: number,
xMax: number,
yMin: number,
yMax: number,
style: Required<CurveStyle>
) {
if (points.length < 2) return;
ctx.save();
if (style.dimmed) {
ctx.globalAlpha = 0.25;
ctx.setLineDash([6, 4]);
}
if (style.fill) {
ctx.beginPath();
points.forEach(({ x, y }, i) => {
const [px, py] = toPx(x, y);
if (i === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
});
const [xEnd, zeroY] = toPx(xMax, 0);
const [xStart] = toPx(xMin, 0);
ctx.lineTo(xEnd, zeroY);
ctx.lineTo(xStart, zeroY);
ctx.closePath();
const [, topY] = toPx(xMin, yMax);
const [, bottomY] = toPx(xMin, yMin);
const gradient = ctx.createLinearGradient(0, topY, 0, bottomY);
gradient.addColorStop(0, style.fillColors.fillAbove);
gradient.addColorStop(0.5, style.fillColors.fillAboveFade);
gradient.addColorStop(0.5, style.fillColors.fillBelowFade);
gradient.addColorStop(1, style.fillColors.fillBelow);
ctx.fillStyle = gradient;
ctx.fill();
}
ctx.beginPath();
points.forEach(({ x, y }, i) => {
const [px, py] = toPx(x, y);
if (i === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
});
ctx.strokeStyle = style.strokeColor;
ctx.lineWidth = style.lineWidth;
ctx.stroke();
ctx.restore();
}
export type DrawCurvesParams = {
ctx: CanvasCtx;
toPx: ToPx;
xMin: number;
xMax: number;
yMin: number;
yMax: number;
/** Each entry is drawn as its own independent polyline. To draw a
* combined curve, sum the point arrays with `sumCurvePoints` first
* and pass the result as a single entry. */
curves: Curve[];
};
/** Generic curve drawer — knows nothing about GEQ/PEQ/crossover. */
export function drawCurves({ ctx, toPx, xMin, xMax, yMin, yMax, curves }: DrawCurvesParams) {
for (const curve of curves) {
const style: Required<CurveStyle> = { ...DEFAULT_STYLE, ...curve.style };
drawSingleCurve(ctx, toPx, curve.points, xMin, xMax, yMin, yMax, style);
}
}
export function buildColorMap<T extends string>(channels: T[]): Record<T, string> {
const map = {} as Record<T, string>;
channels.forEach((ch, i) => {
map[ch] = CHANNEL_COLORS[i % CHANNEL_COLORS.length];
});
return map;
}