topo-canvas.tsx 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. "use client";
  2. import { useEffect, useRef } from "react";
  3. import { onIdle } from "@/lib/utils";
  4. type TopoFile = {
  5. w: number;
  6. h: number;
  7. summit: [number, number];
  8. levels: { e: number; l: number[][] }[];
  9. };
  10. type Topo = Omit<TopoFile, "levels"> & {
  11. levels: { e: number; lines: Float32Array[] }[];
  12. };
  13. function decode(file: TopoFile): Topo {
  14. return {
  15. ...file,
  16. levels: file.levels.map(({ e, l }) => ({
  17. e,
  18. lines: l.map((flat) => {
  19. const pts = new Float32Array(flat.length);
  20. let x = 0;
  21. let y = 0;
  22. for (let i = 0; i < flat.length; i += 2) {
  23. x += flat[i];
  24. y += flat[i + 1];
  25. pts[i] = x;
  26. pts[i + 1] = y;
  27. }
  28. return pts;
  29. }),
  30. })),
  31. };
  32. }
  33. /** Where the summit sits on screen, and how much to scale so the map covers the viewport. */
  34. function layout(topo: Topo, w: number, h: number) {
  35. const narrow = w < 640;
  36. const sx = w * (narrow ? 0.78 : 0.84);
  37. const sy = h * (narrow ? 0.06 : 0.08);
  38. const [ux, uy] = topo.summit;
  39. const s =
  40. Math.max(
  41. sx / ux,
  42. (w - sx) / (topo.w - ux),
  43. sy / uy,
  44. (h - sy) / (topo.h - uy),
  45. narrow ? 0.9 : 1.15,
  46. ) * 1.02;
  47. return { sx, sy, s, ox: sx - ux * s, oy: sy - uy * s };
  48. }
  49. function drawContours(
  50. canvas: HTMLCanvasElement,
  51. topo: Topo,
  52. color: string,
  53. weight: number,
  54. ) {
  55. const w = canvas.clientWidth;
  56. const h = canvas.clientHeight;
  57. const dpr = Math.min(window.devicePixelRatio || 1, 2);
  58. const { s, ox, oy } = layout(topo, w, h);
  59. canvas.width = Math.round(w * dpr);
  60. canvas.height = Math.round(h * dpr);
  61. const ctx = canvas.getContext("2d");
  62. if (!ctx) return;
  63. ctx.setTransform(dpr * s, 0, 0, dpr * s, dpr * ox, dpr * oy);
  64. ctx.strokeStyle = color;
  65. ctx.lineJoin = "round";
  66. ctx.lineCap = "round";
  67. for (const level of topo.levels) {
  68. const index = level.e % 600 === 0;
  69. ctx.lineWidth = ((index ? 1.7 : 1) * weight) / s;
  70. ctx.globalAlpha = index ? 1 : 0.75;
  71. ctx.beginPath();
  72. for (const p of level.lines) {
  73. ctx.moveTo(p[0], p[1]);
  74. // Smooth the simplified polyline with quadratic curves through midpoints.
  75. for (let i = 2; i < p.length - 2; i += 2) {
  76. ctx.quadraticCurveTo(
  77. p[i],
  78. p[i + 1],
  79. (p[i] + p[i + 2]) / 2,
  80. (p[i + 1] + p[i + 3]) / 2,
  81. );
  82. }
  83. ctx.lineTo(p[p.length - 2], p[p.length - 1]);
  84. }
  85. ctx.stroke();
  86. }
  87. }
  88. /**
  89. * Real contour lines of Mount Rainier (Tahoma), the mountain I'm training to
  90. * climb, drawn once after the page is idle and again only on resize or theme
  91. * change, so the glass above it never has to re-blur a moving background.
  92. */
  93. export function TopoCanvas() {
  94. const wrapRef = useRef<HTMLDivElement>(null);
  95. const canvasRef = useRef<HTMLCanvasElement>(null);
  96. useEffect(() => {
  97. let topo: Topo | null = null;
  98. let disposed = false;
  99. let resizeTimer = 0;
  100. let lastWidth = 0;
  101. const paint = () => {
  102. const canvas = canvasRef.current;
  103. if (!topo || disposed || !canvas) return;
  104. const css = getComputedStyle(document.documentElement);
  105. lastWidth = canvas.clientWidth;
  106. drawContours(canvas, topo, css.getPropertyValue("--topo").trim(), 1);
  107. wrapRef.current?.setAttribute("data-ready", "true");
  108. };
  109. const load = () =>
  110. fetch("/data/rainier-topo.json")
  111. .then((r) => r.json())
  112. .then((file: TopoFile) => {
  113. topo = decode(file);
  114. paint();
  115. })
  116. .catch(() => {});
  117. const cancelIdle = onIdle(load, 2500);
  118. const onResize = () => {
  119. window.clearTimeout(resizeTimer);
  120. resizeTimer = window.setTimeout(() => {
  121. // Mobile toolbars change only the height; the backdrop is sized to the
  122. // large viewport, so only a width change needs a redraw.
  123. if (canvasRef.current?.clientWidth !== lastWidth) paint();
  124. }, 160);
  125. };
  126. const themeObserver = new MutationObserver(paint);
  127. themeObserver.observe(document.documentElement, {
  128. attributes: true,
  129. attributeFilter: ["class"],
  130. });
  131. window.addEventListener("resize", onResize);
  132. return () => {
  133. disposed = true;
  134. cancelIdle();
  135. window.clearTimeout(resizeTimer);
  136. themeObserver.disconnect();
  137. window.removeEventListener("resize", onResize);
  138. };
  139. }, []);
  140. return (
  141. <div
  142. ref={wrapRef}
  143. className="absolute inset-0 opacity-0 transition-opacity duration-1000 data-[ready=true]:opacity-100"
  144. >
  145. <canvas ref={canvasRef} className="absolute inset-0 size-full" />
  146. </div>
  147. );
  148. }