/** * ResultCanvas * Optional intro animation: circles draw in one-by-one (arc sweep) with a count-up. * Interactive phase: zoom/pan + edit tools. Tap during intro to skip to the final frame. */ import { useEffect, useRef, useState } from 'react' import { isLowMemoryDevice } from '../lib/inference' import type { Detection, DiameterGroup, CircleLabelMode, ToolMode } from '../lib/types' /** * Render scale for the result canvas. * * Drawing the photo at full resolution (e.g. a 12 MP phone photo => ~48 MB * canvas, redrawn every animation frame) can crash the tab on low-RAM devices. * We cap the canvas buffer size and use ctx.setTransform() so all detection * coordinate math can stay in natural pixels. Capable devices keep near-full * resolution so the result stays crisp. */ function computeRenderScale(naturalW: number, naturalH: number): number { const longSide = Math.max(naturalW, naturalH) const cap = isLowMemoryDevice() ? 2200 : 4096 return Math.min(1, cap / longSide) } // --------------------------------------------------------------------------- // helpers // --------------------------------------------------------------------------- function hexToRgb(hex: string): [number, number, number] { const v = parseInt(hex.replace('#', ''), 16) return [(v >> 16) & 255, (v >> 8) & 255, v & 255] } function easeOut(t: number): number { return 1 - (1 - t) * (1 - t) } interface RankedDet { d: Detection label: number } function sortSpatially(detections: Detection[]): RankedDet[] { const items = detections.map((d) => ({ d, cy: (d.ymin + d.ymax) / 2, cx: (d.xmin + d.xmax) / 2, h: d.ymax - d.ymin, })) const heights = items.map((x) => x.h).sort((a, b) => a - b) const medianH = heights[Math.floor(heights.length / 2)] ?? 40 const rowTol = Math.max(14, medianH * 0.45) return items .sort((a, b) => { if (Math.abs(a.cy - b.cy) > rowTol) return a.cy - b.cy return a.cx - b.cx }) .map((item, i) => ({ d: item.d, label: i + 1 })) } function spatialLabelMap(detections: Detection[]): WeakMap { const map = new WeakMap() for (const { d, label } of sortSpatially(detections)) { map.set(d, label) } return map } function detectionCircleLabel( d: Detection, mode: 'count' | 'confidence', countLabels: WeakMap, ): string { if (mode === 'confidence') { return d.confidence.toFixed(2) } const n = countLabels.get(d) return n !== undefined ? String(n) : '' } function computeStagger(count: number): { staggerMs: number; durationMs: number } { if (count <= 500) return { staggerMs: 8, durationMs: 220 } if (count <= 1000) return { staggerMs: 4, durationMs: 150 } return { staggerMs: 2, durationMs: 100 } } /** * Radius for a detection circle so it sits INSIDE the pipe's box and does not * touch its neighbours. We leave a 12% gap and also reserve room for the stroke * (which is centred on the path and extends outward by lineWidth/2), so the * painted circle never spills past the box edge. */ function fitRadius(pw: number, ph: number, minR: number): number { const halfBox = Math.min(pw, ph) / 2 // gap so adjacent circles stay visually separated const target = halfBox * 0.86 // never exceed the box (keeps tiny detections from overflowing too) return Math.min(Math.max(minR, target), halfBox) } /** * Font size so the label fits inside the circle without touching the stroke. * Uses canvas measureText for real width/height instead of a digit-count guess. */ function fitLabelFontSize( ctx: CanvasRenderingContext2D, label: string, radius: number, displayPx: number, ): number { const minFs = 5 / displayPx let fs = Math.min(radius * 0.82, 13 / displayPx) const maxW = radius * 2 * 0.66 const maxH = radius * 2 * 0.5 for (let i = 0; i < 16; i++) { ctx.font = `bold ${fs}px system-ui, -apple-system, sans-serif` const m = ctx.measureText(label) const w = m.width const h = (m.actualBoundingBoxAscent ?? fs * 0.8) + (m.actualBoundingBoxDescent ?? fs * 0.2) if (w <= maxW && h <= maxH) break fs = Math.max(minFs, fs * 0.84) } return Math.max(minFs, fs) } /** * Draw a single detection circle at full image resolution. * @param displayPx CSS pixels per canvas pixel (used to scale strokes/fonts to look right) */ function drawCircle( ctx: CanvasRenderingContext2D, cx: number, cy: number, radius: number, rgb: [number, number, number], progress: number, label: string, showLabel: boolean, displayPx: number, ) { const [r, g, b] = rgb const eased = easeOut(Math.min(1, progress)) // thin stroke: ~1 CSS px minimum, scaling gently with radius const lw = Math.max(1 / displayPx, radius * 0.07) ctx.save() // semi-transparent fill (fades in) ctx.beginPath() ctx.arc(cx, cy, radius, 0, Math.PI * 2) ctx.fillStyle = `rgba(${r},${g},${b},${0.30 * eased})` ctx.fill() // stroke arc sweeps clockwise from 12 o'clock ctx.beginPath() const endAngle = progress >= 1 ? Math.PI * 2 : eased * Math.PI * 2 ctx.arc(cx, cy, radius, -Math.PI / 2, -Math.PI / 2 + endAngle) ctx.strokeStyle = `rgba(${r},${g},${b},0.92)` ctx.lineWidth = lw ctx.lineCap = 'round' ctx.stroke() // number label — centred in the circle using glyph bounding box if (showLabel && label && eased > 0) { const alpha = Math.min(1, eased * 2) const fs = fitLabelFontSize(ctx, label, radius, displayPx) ctx.font = `bold ${fs}px system-ui, -apple-system, sans-serif` ctx.textAlign = 'center' ctx.textBaseline = 'alphabetic' const m = ctx.measureText(label) const ascent = m.actualBoundingBoxAscent ?? fs * 0.8 const descent = m.actualBoundingBoxDescent ?? fs * 0.22 // place baseline so the glyph visual centre sits at cy const baselineY = cy + (ascent - descent) / 2 ctx.save() ctx.beginPath() ctx.arc(cx, cy, Math.max(1, radius - lw * 0.55), 0, Math.PI * 2) ctx.clip() const outline = Math.max(0.35 / displayPx, fs * 0.08) ctx.lineJoin = 'round' ctx.lineWidth = outline ctx.strokeStyle = `rgba(0,0,0,${0.6 * alpha})` ctx.fillStyle = `rgba(255,255,255,${alpha})` ctx.strokeText(label, cx, baselineY) ctx.fillText(label, cx, baselineY) ctx.restore() } ctx.restore() } // --------------------------------------------------------------------------- // component // --------------------------------------------------------------------------- function computeFitSize( imageW: number, imageH: number, bounds: { w: number; h: number } | null, parentW: number, ): { cssW: number; cssH: number; displayPx: number } { const aspect = imageH / Math.max(imageW, 1) if (!bounds || bounds.w <= 0 || bounds.h <= 0) { const cssW = parentW return { cssW, cssH: cssW * aspect, displayPx: cssW / imageW } } let cssW = bounds.w let cssH = cssW * aspect if (cssH > bounds.h) { cssH = bounds.h cssW = cssH / aspect } return { cssW, cssH, displayPx: cssW / imageW } } interface Props { image: HTMLImageElement detections: Detection[] groups: DiameterGroup[] tool: ToolMode selectedGroupId: number displayBounds?: { w: number; h: number } | null /** When false (default), circles render immediately with no count-up animation. */ animate?: boolean /** Number labels inside circles — hide during intro animation, show on results dock. */ showCircleLabels?: boolean /** Show spatial count (default) or model confidence for debugging. */ circleLabelMode?: CircleLabelMode onUpdate: (dets: Detection[]) => void onCanvasReady?: (canvas: HTMLCanvasElement | null) => void onAnimationComplete?: () => void /** ref to a DOM element whose textContent will be updated with live count */ countDisplayRef?: React.RefObject } export function ResultCanvas({ image, detections, groups, tool, selectedGroupId, displayBounds, animate = false, showCircleLabels = true, circleLabelMode = 'count', onUpdate, onCanvasReady, onAnimationComplete, countDisplayRef, }: Props) { const containerRef = useRef(null) const canvasRef = useRef(null) const [animating, setAnimating] = useState(animate) const skipRef = useRef(false) const rafRef = useRef(0) const introPlayedRef = useRef(false) const imageRef = useRef(image) if (image !== imageRef.current) { imageRef.current = image introPlayedRef.current = false } // zoom / pan state (used in interactive phase) const transformRef = useRef({ scale: 1, tx: 0, ty: 0 }) const [displayScale, setDisplayScale] = useState(1) const activeRef = useRef(new Map()) const pinchRef = useRef<{ dist: number; mx: number; my: number } | null>(null) const panStartRef = useRef<{ x: number; y: number; tx: number; ty: number } | null>(null) const areaStartRef = useRef<{ x: number; y: number } | null>(null) const areaRef = useRef<{ x1: number; y1: number; x2: number; y2: number } | null>(null) const lastTapRef = useRef(0) // ------------------------------------------------------------------------- // animation phase // ------------------------------------------------------------------------- useEffect(() => { if (detections.length === 0) { setAnimating(false) introPlayedRef.current = false onAnimationComplete?.() return } const canvas = canvasRef.current if (!canvas) return const ctx = canvas.getContext('2d') if (!ctx) return // After the intro animation, layout-only changes (e.g. dock appearing) must not replay it. if (introPlayedRef.current && animate) { setAnimating(false) return } // Canvas buffer is capped on low-memory devices; ctx.setTransform(rs,rs) // lets all drawing below keep using natural-pixel coordinates. CSS // width:100% then scales the buffer to the display width. const rs = computeRenderScale(image.naturalWidth, image.naturalHeight) const parentW = canvas.parentElement?.clientWidth ?? image.naturalWidth const { cssW, cssH, displayPx } = computeFitSize( image.naturalWidth, image.naturalHeight, displayBounds ?? null, parentW, ) const container = containerRef.current if (container) { container.style.width = displayBounds ? `${cssW}px` : '100%' container.style.height = displayBounds ? `${cssH}px` : 'auto' container.style.margin = displayBounds ? '0 auto' : '' container.style.maxHeight = displayBounds ? `${cssH}px` : '' } canvas.style.width = displayBounds ? `${cssW}px` : '100%' canvas.style.height = displayBounds ? `${cssH}px` : 'auto' const natW = image.naturalWidth const natH = image.naturalHeight canvas.width = Math.round(natW * rs) canvas.height = Math.round(natH * rs) ctx.setTransform(rs, 0, 0, rs, 0, 0) onCanvasReady?.(canvas) if (!animate) { setAnimating(false) introPlayedRef.current = true onAnimationComplete?.() return } setAnimating(true) const sorted = sortSpatially(detections) const { staggerMs, durationMs } = computeStagger(detections.length) const totalMs = (sorted.length - 1) * staggerMs + durationMs const dense = detections.length > 300 // minimum circle radius expressed in CSS pixels → converted to natural px const minR = (dense ? 5 : 7) / displayPx let startTs: number | null = null skipRef.current = false function frame(ts: number) { if (!canvas) return if (startTs === null) startTs = ts const elapsed = skipRef.current ? totalMs + 1 : ts - startTs ctx!.clearRect(0, 0, natW, natH) ctx!.drawImage(image, 0, 0, natW, natH) let visibleCount = 0 sorted.forEach(({ d, label }, animIdx) => { const startAt = animIdx * staggerMs if (elapsed < startAt) return const progress = (elapsed - startAt) / durationMs const group = groups.find((g) => g.id === d.groupId) ?? groups[0] const color = group?.color ?? '#ef4444' const rgb = hexToRgb(color) // coords already in natural image pixels (ds = 1) const pw = d.xmax - d.xmin const ph = d.ymax - d.ymin const cx = d.xmin + pw / 2 const cy = d.ymin + ph / 2 const radius = fitRadius(pw, ph, minR) drawCircle(ctx!, cx, cy, radius, rgb, progress, String(label), false, displayPx) visibleCount++ }) // live count update (DOM-direct for perf — avoids React re-renders) if (countDisplayRef?.current) { countDisplayRef.current.textContent = String(visibleCount) } if (elapsed < totalMs) { rafRef.current = requestAnimationFrame(frame) } else { // final static redraw with all circles fully complete ctx!.clearRect(0, 0, natW, natH) ctx!.drawImage(image, 0, 0, natW, natH) sorted.forEach(({ d, label }) => { const group = groups.find((g) => g.id === d.groupId) ?? groups[0] const color = group?.color ?? '#ef4444' const rgb = hexToRgb(color) const pw = d.xmax - d.xmin const ph = d.ymax - d.ymin const cx = d.xmin + pw / 2 const cy = d.ymin + ph / 2 const radius = fitRadius(pw, ph, minR) drawCircle(ctx!, cx, cy, radius, rgb, 1, String(label), false, displayPx) }) if (countDisplayRef?.current) { countDisplayRef.current.textContent = String(detections.length) } introPlayedRef.current = true setAnimating(false) onAnimationComplete?.() } } rafRef.current = requestAnimationFrame(frame) return () => cancelAnimationFrame(rafRef.current) // eslint-disable-next-line react-hooks/exhaustive-deps }, [image, detections, groups, displayBounds, animate]) // Reset pan/zoom when the canvas is re-fitted above the results dock. useEffect(() => { if (!displayBounds) return transformRef.current = { scale: 1, tx: 0, ty: 0 } setDisplayScale(1) const canvas = canvasRef.current if (canvas) canvas.style.transform = '' }, [displayBounds?.w, displayBounds?.h]) // ------------------------------------------------------------------------- // interactive phase – re-render on detections / groups change // ------------------------------------------------------------------------- useEffect(() => { if (animating) return const canvas = canvasRef.current if (!canvas || !image) return const ctx = canvas.getContext('2d') if (!ctx) return // Keep the (capped) canvas buffer in sync with the image. const rs = computeRenderScale(image.naturalWidth, image.naturalHeight) const natW = image.naturalWidth const natH = image.naturalHeight const scaledW = Math.round(natW * rs) if (canvas.width !== scaledW) { canvas.width = scaledW canvas.height = Math.round(natH * rs) } const parentW = canvas.parentElement?.clientWidth ?? natW const { cssW, cssH, displayPx } = computeFitSize(natW, natH, displayBounds ?? null, parentW) const container = containerRef.current if (container && displayBounds) { container.style.width = `${cssW}px` container.style.height = `${cssH}px` container.style.margin = '0 auto' container.style.maxHeight = `${cssH}px` canvas.style.width = `${cssW}px` canvas.style.height = `${cssH}px` } else if (container) { container.style.width = '100%' container.style.height = 'auto' container.style.margin = '' container.style.maxHeight = '' canvas.style.width = '100%' canvas.style.height = 'auto' } ctx.setTransform(rs, 0, 0, rs, 0, 0) ctx.clearRect(0, 0, natW, natH) ctx.drawImage(image, 0, 0, natW, natH) const dense = detections.length > 300 const showLabels = showCircleLabels && detections.length <= 3000 const minR = (dense ? 5 : 7) / displayPx const labels = spatialLabelMap(detections) detections.forEach((d) => { const group = groups.find((g) => g.id === d.groupId) ?? groups[0] const color = group?.color ?? '#ef4444' const rgb = hexToRgb(color) const pw = d.xmax - d.xmin const ph = d.ymax - d.ymin const cx = d.xmin + pw / 2 const cy = d.ymin + ph / 2 const radius = fitRadius(pw, ph, minR) const label = detectionCircleLabel(d, circleLabelMode, labels) drawCircle(ctx, cx, cy, radius, rgb, 1, label, showLabels && Boolean(label), displayPx) }) const area = areaRef.current if (area) { ctx.save() ctx.strokeStyle = 'rgba(255,255,255,0.9)' ctx.fillStyle = 'rgba(255,255,255,0.08)' ctx.lineWidth = Math.max(2 / displayPx, 1) ctx.setLineDash([6 / displayPx, 4 / displayPx]) ctx.fillRect(area.x1, area.y1, area.x2 - area.x1, area.y2 - area.y1) ctx.strokeRect(area.x1, area.y1, area.x2 - area.x1, area.y2 - area.y1) ctx.restore() } }, [animating, image, detections, groups, displayBounds, showCircleLabels, circleLabelMode]) // ------------------------------------------------------------------------- // direct canvas redraw — does NOT go through React state / onUpdate // use this for transient visual updates (area rect, post-pan) to avoid // triggering React re-renders and the canvas useEffect. // ------------------------------------------------------------------------- const redrawCanvas = () => { const canvas = canvasRef.current if (!canvas || !image || animating) return const ctx = canvas.getContext('2d') if (!ctx) return const rs = computeRenderScale(image.naturalWidth, image.naturalHeight) const natW = image.naturalWidth const natH = image.naturalHeight const parentW = canvas.parentElement?.clientWidth ?? natW const { displayPx } = computeFitSize(natW, natH, displayBounds ?? null, parentW) const dense = detections.length > 300 const showLabels = showCircleLabels && detections.length <= 3000 const minR = (dense ? 5 : 7) / displayPx ctx.setTransform(rs, 0, 0, rs, 0, 0) ctx.clearRect(0, 0, natW, natH) ctx.drawImage(image, 0, 0, natW, natH) const labels = spatialLabelMap(detections) detections.forEach((d) => { const group = groups.find((g) => g.id === d.groupId) ?? groups[0] const rgb = hexToRgb(group?.color ?? '#ef4444') const pw = d.xmax - d.xmin const ph = d.ymax - d.ymin const label = detectionCircleLabel(d, circleLabelMode, labels) drawCircle( ctx, d.xmin + pw / 2, d.ymin + ph / 2, fitRadius(pw, ph, minR), rgb, 1, label, showLabels && Boolean(label), displayPx, ) }) const area = areaRef.current if (area) { ctx.save() ctx.strokeStyle = 'rgba(255,255,255,0.9)' ctx.fillStyle = 'rgba(255,255,255,0.08)' ctx.lineWidth = Math.max(2 / displayPx, 1) ctx.setLineDash([6 / displayPx, 4 / displayPx]) ctx.fillRect(area.x1, area.y1, area.x2 - area.x1, area.y2 - area.y1) ctx.strokeRect(area.x1, area.y1, area.x2 - area.x1, area.y2 - area.y1) ctx.restore() } } // ------------------------------------------------------------------------- // zoom / pan helpers (interactive phase only) // ------------------------------------------------------------------------- const applyTransform = () => { const canvas = canvasRef.current if (!canvas) return const { scale, tx, ty } = transformRef.current canvas.style.transform = `translate(${tx}px,${ty}px) scale(${scale})` setDisplayScale(scale) } const clampTransform = () => { const canvas = canvasRef.current const container = containerRef.current if (!canvas || !container) return const t = transformRef.current if (t.scale <= 1) { transformRef.current = { scale: 1, tx: 0, ty: 0 } } else { const cw = container.clientWidth const ch = container.clientHeight const lw = canvas.offsetWidth const lh = canvas.offsetHeight t.tx = Math.min(0, Math.max(cw - lw * t.scale, t.tx)) t.ty = Math.min(0, Math.max(ch - lh * t.scale, t.ty)) } setDisplayScale(transformRef.current.scale) applyTransform() } const resetZoom = () => { transformRef.current = { scale: 1, tx: 0, ty: 0 } setDisplayScale(1) applyTransform() } const toImageCoords = (clientX: number, clientY: number) => { const canvas = canvasRef.current! const rect = canvas.getBoundingClientRect() return { x: ((clientX - rect.left) / rect.width) * image.naturalWidth, y: ((clientY - rect.top) / rect.height) * image.naturalHeight, } } const findHit = (x: number, y: number) => { for (let i = detections.length - 1; i >= 0; i--) { const d = detections[i] if (x >= d.xmin && x <= d.xmax && y >= d.ymin && y <= d.ymax) return i } return -1 } // ------------------------------------------------------------------------- // pointer event handlers // ------------------------------------------------------------------------- const handlePointerDown = (e: React.PointerEvent) => { // skip animation on tap if (animating) { skipRef.current = true return } e.currentTarget.setPointerCapture(e.pointerId) activeRef.current.set(e.pointerId, { x: e.clientX, y: e.clientY }) if (activeRef.current.size === 2) { panStartRef.current = null areaStartRef.current = null const pts = [...activeRef.current.values()] const dist = Math.hypot(pts[1].x - pts[0].x, pts[1].y - pts[0].y) pinchRef.current = { dist, mx: (pts[0].x + pts[1].x) / 2, my: (pts[0].y + pts[1].y) / 2 } return } if (activeRef.current.size > 2) return const now = Date.now() if (now - lastTapRef.current < 280) { resetZoom() lastTapRef.current = 0 return } lastTapRef.current = now if (transformRef.current.scale > 1 || tool === 'view') { panStartRef.current = { x: e.clientX, y: e.clientY, tx: transformRef.current.tx, ty: transformRef.current.ty } return } const { x, y } = toImageCoords(e.clientX, e.clientY) if (tool === 'area') { areaStartRef.current = { x, y } areaRef.current = { x1: x, y1: y, x2: x, y2: y } return } const hit = findHit(x, y) if (tool === 'delete' && hit >= 0) { onUpdate(detections.filter((_, i) => i !== hit)); return } if (tool === 'reassign' && hit >= 0) { onUpdate(detections.map((d, i) => i === hit ? { ...d, groupId: selectedGroupId, manual: true } : d)); return } if (tool === 'add') { const s = 24 onUpdate([...detections, { id: `m-${Date.now()}`, xmin: x - s / 2, ymin: y - s / 2, xmax: x + s / 2, ymax: y + s / 2, confidence: 1, groupId: selectedGroupId, manual: true }]) } } const handlePointerMove = (e: React.PointerEvent) => { if (animating || !activeRef.current.has(e.pointerId)) return activeRef.current.set(e.pointerId, { x: e.clientX, y: e.clientY }) if (activeRef.current.size === 2 && pinchRef.current) { const pts = [...activeRef.current.values()] const dist = Math.hypot(pts[1].x - pts[0].x, pts[1].y - pts[0].y) const mx = (pts[0].x + pts[1].x) / 2 const my = (pts[0].y + pts[1].y) / 2 const t = transformRef.current const newScale = Math.max(1, Math.min(6, t.scale * (dist / pinchRef.current.dist))) const container = containerRef.current if (container) { const cr = container.getBoundingClientRect() const lx = mx - cr.left, ly = my - cr.top const ox = (lx - t.tx) / t.scale, oy = (ly - t.ty) / t.scale t.tx = lx - ox * newScale + (mx - pinchRef.current.mx) t.ty = ly - oy * newScale + (my - pinchRef.current.my) } t.scale = newScale clampTransform() pinchRef.current = { dist, mx, my } return } if (panStartRef.current && activeRef.current.size === 1) { transformRef.current.tx = panStartRef.current.tx + e.clientX - panStartRef.current.x transformRef.current.ty = panStartRef.current.ty + e.clientY - panStartRef.current.y clampTransform() return } if (areaStartRef.current && tool === 'area') { const { x, y } = toImageCoords(e.clientX, e.clientY) areaRef.current = { x1: Math.min(areaStartRef.current.x, x), y1: Math.min(areaStartRef.current.y, y), x2: Math.max(areaStartRef.current.x, x), y2: Math.max(areaStartRef.current.y, y), } // draw the selection rect directly — no React state update needed redrawCanvas() } } const handlePointerUp = (e: React.PointerEvent) => { if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId) if (!animating && tool === 'area' && areaStartRef.current) { const a = areaRef.current areaRef.current = null areaStartRef.current = null if (a && a.x2 > a.x1 && a.y2 > a.y1) { // area was drawn — update detections (this triggers re-render + canvas useEffect) onUpdate(detections.map((d) => { const cx = (d.xmin + d.xmax) / 2, cy = (d.ymin + d.ymax) / 2 return cx >= a.x1 && cx <= a.x2 && cy >= a.y1 && cy <= a.y2 ? { ...d, groupId: selectedGroupId, manual: true } : d })) } else { // no area drawn — just clear the rect from canvas without a state update redrawCanvas() } } activeRef.current.delete(e.pointerId) if (activeRef.current.size < 2) pinchRef.current = null if (activeRef.current.size === 0) { panStartRef.current = null // ← removed onUpdate([...detections]) — that was causing redraws on every tap } } return (
{/* animation skip hint */} {animating && (
Tap to skip
)} {/* zoom badge */} {!animating && displayScale > 1.05 && ( )} {/* zoom hint after animation */} {!animating && displayScale <= 1.05 && detections.length > 0 && (
Pinch to zoom · double-tap reset
)}
) }