2546961Plate mechanics lab: Kirchhoff-Love plates solved by numbl in the browserJeremy Magland 1import { useEffect, useRef } from "react";
2import { colormapTable, getColormap, type Range } from "@plate-lab/core";
4export function Colorbar({ range, colormap, unit, scale = 1, height = 200 }: { range: Range; colormap: string; unit?: string; scale?: number; height?: number }) {
5 const ref = useRef<HTMLCanvasElement>(null);
6 useEffect(() => {
7 const c = ref.current;
8 if (!c) return;
9 const ctx = c.getContext("2d");
10 if (!ctx) return;
11 const table = colormapTable(getColormap(colormap));
12 const h = 256;
13 c.width = 1;
14 c.height = h;
15 const img = ctx.createImageData(1, h);
16 for (let k = 0; k < h; k++) {
17 const t = 255 - k;
18 img.data[4 * k] = table[3 * t];
19 img.data[4 * k + 1] = table[3 * t + 1];
20 img.data[4 * k + 2] = table[3 * t + 2];
21 img.data[4 * k + 3] = 255;
22 }
23 ctx.putImageData(img, 0, 0);
24 }, [colormap]);
25 return (
26 <div className="pl-colorbar" style={{ height }}>
27 <span>{fmt(range.max * scale)}</span>
28 <canvas ref={ref} />
29 <span>
30 {fmt(range.min * scale)} {unit}
31 </span>
32 </div>
33 );
34}
36export function fmt(x: number): string {
37 if (x === 0) return "0";
38 const a = Math.abs(x);
39 if (a >= 1e4 || a < 1e-2) return x.toExponential(2);
40 return x.toPrecision(3);
41}