Generating Cut-Ready Stained Glass SVGs in Pure Browser JS: Shared Half-Edges, Copper Foil Kerf Offsets & Concave Fracture Checks

2026-11-16来源 dev.toEnglish

Feed a segmented image into a standard raster-to-SVG tracer (potrace, imagetracerjs, or Illustrator Image Trace), send that SVG to a Cricut Maker to cut adhesive vinyl stencils for stained glass, and three physical bugs show up at the workbench within twenty minutes:

  1. Shredded vinyl bridges: Every interior line between two glass pieces gets sliced twice by the plotter blade, peeling narrow 1 mm stencil tracks right off the backing sheet.
  2. Panels that outgrow their wood frames: Cut 14 glass pieces across an 18" window panel from zero-gap polygons, wrap each edge in 7/32" copper foil tape, tin the seams with 60/40 solder, and your finished glass panel ends up nearly 1/2" wider than the oak frame you milled for it.
  3. Impossible inside corners: Vector tracers happily output 250° L-notches and crescent pockets that look fine on a monitor, then snap straight across the waist the second you squeeze running pliers on 3 mm cathedral glass.

While building the client-side vector engine behind Stained Glass Pattern Generator, I pulled the core geometry algorithms into a standalone, zero-dependency ES module: stained-glass-svg-math (with an interactive field verifier on GitHub Pages). Here is how each physical constraint translates into clean browser JavaScript.

Bug 1: Double-Stroked Polygon Edges Shred Cricut Stencils

When you segment a photo into integer region IDs (via superpixels, K-means palette clustering, or Voronoi cells, like we do in our photo to stained glass pattern converter), the naive way to build an SVG is to walk the contour of Region 1, emit a <polygon>, walk Region 2, and emit another <polygon>.

Along every shared interior seam, Region 1 emits directed edge (u -> v) and Region 2 emits the opposite twin (v -> u). On screen, two overlapping 1px strokes look like a single black line. On a vinyl cutter or CO2 laser, the toolhead physically traverses that seam twice.

The fix is topological half-edge deduplication over the 2D label grid before any path simplification happens:

  1. Emit directed unit boundary half-edges around every grid cell (r, c) wherever a neighbor has a different region ID (using null for outside the canvas).
  2. Collapse opposite half-edges (u -> v) and (v -> u) onto a canonical undirected edge key min(u, v) | max(u, v).
  3. Count vertex degrees in the deduplicated undirected graph. Any vertex with degree >= 3 is a topological solder junction (a 3-way T-joint or 4-way X-joint).
  4. Trace maximal open chains between junctions, locking junction coordinates before running collinear or Ramer-Douglas-Peucker simplification so adjacent pieces never tear open into T-cracks.
export function extractCanonicalUnitEdges(grid) { const rows = grid.length; const cols = grid[0].length; const unitEdges = new Map(); let directedHalfEdgeCount = 0; const addHalfEdge = (sx, sy, ex, ey, region, neighbor) => { directedHalfEdgeCount++; const forward = sx < ex || (sx === ex && sy < ey); const key = forward ? `${sx},${sy}|${ex},${ey}` : `${ex},${ey}|${sx},${sy}`; if (!unitEdges.has(key)) { unitEdges.set(key, { ax: forward ? sx : ex, ay: forward ? sy : ey, bx: forward ? ex : sx, by: forward ? ey : sy, isInteriorSeam: neighbor !== null, regions: neighbor === null ? [region] : [region, neighbor], }); } }; for (let r = 0; r < rows; r++) { for (let c = 0; c < cols; c++) { const id = grid[r][c]; if (r === 0 || grid[r - 1][c] !== id) addHalfEdge(c, r, c + 1, r, id, r > 0 ? grid[r - 1][c] : null); if (c + 1 === cols || grid[r][c + 1] !== id) addHalfEdge(c + 1, r, c + 1, r + 1, id, c + 1 < cols ? grid[r][c + 1] : null); if (r + 1 === rows || grid[r + 1][c] !== id) addHalfEdge(c + 1, r + 1, c, r + 1, id, r + 1 < rows ? grid[r + 1][c] : null); if (c === 0 || grid[r][c - 1] !== id) addHalfEdge(c, r + 1, c, r, id, c > 0 ? grid[r][c - 1] : null); } } return { directedHalfEdgeCount, uniqueUnitEdgeCount: unitEdges.size, duplicateEdgesEliminated: directedHalfEdgeCount - unitEdges.size, edges: [...unitEdges.values()], }; } 

On a typical 30-piece pattern, deduplicating shared interior seams eliminates 28% to 42% of total cutter travel and guarantees single-pass scoring in tools like our SVG stained glass pattern and Cricut stencil generator.

Bug 2: Zero-Gap Polygons Cause 1/2" Panel Creep

In traditional hand-drawn stained glass cartoons, artisans cut paper templates apart using 3-bladed pattern shears. Those shears slice out a thin center ribbon of paper along every seam:

  • Standard 7/32" copper foil: 0.90 mm (0.036") total seam channel (0.45 mm / 0.018" inset per adjacent piece).
  • Heavy 1/4" foil / textured architectural glass: 1.20 mm (0.047") total seam channel (0.60 mm per piece).
  • Traditional 5/64" lead came heart: 2.00 mm (0.079") total heart allowance (1.00 mm per piece).

Skip that offset on a panel that spans 14 glass pieces horizontally (13 interior joints), and 13 * 0.90 mm = 11.7 mm (0.461") of copper tape, acrylic adhesive, and capillary solder accumulates across the width.

To inset each glass polygon cleanly in browser JS without pulling in a 200 KB polygon-clipping dependency, two subtle traps matter:

  1. Winding orientation flips between Cartesian and SVG coordinates: In SVG (+x right, +y down), a clockwise loop has positive signed shoelace area, whereas in Cartesian math (+y up), counter-clockwise is positive. Hardcoding (-ty, tx) without multiplying by Math.sign(signedArea) will randomly inflate polygons outward instead of shrinking them inward.
  2. Acute corners explode without a miter limit: At a sharp 15° glass shard tip, the raw bisector distance d / sin(theta / 2) shoots 7.66 * d deep into the piece. Clamping vertex shift to miterLimit * d (3.0 * d) keeps sharp tips well-behaved.
export function signedPolygonArea(pts) { let sum = 0; for (let i = 0; i < pts.length; i++) { const a = pts[i]; const b = pts[(i + 1) % pts.length]; sum += a.x * b.y - b.x * a.y; } return sum * 0.5; } export function computeKerfInsetPolygon(pts, { kerfMm = 0.9, unitsPerMm = 1, miterLimit = 3.0 } = {}) { const areaSigned = signedPolygonArea(pts); const orientation = areaSigned >= 0 ? 1 : -1; const d = (kerfMm * 0.5) * unitsPerMm; // Each side of a shared seam shrinks by kerf / 2 const edges = pts.map((a, i) => { const b = pts[(i + 1) % pts.length]; const len = Math.hypot(b.x - a.x, b.y - a.y); const tx = (b.x - a.x) / len; const ty = (b.y - a.y) / len; // Winding-invariant inward unit normal return { tx, ty, nx: orientation * -ty, ny: orientation * tx }; }); return pts.map((p, i) => { const prev = edges[(i - 1 + pts.length) % pts.length]; const curr = edges[i]; const q0x = p.x + d * prev.nx, q0y = p.y + d * prev.ny; const q1x = p.x + d * curr.nx, q1y = p.y + d * curr.ny; const denom = prev.tx * curr.ty - prev.ty * curr.tx; let ix, iy; if (Math.abs(denom) < 1e-8) { ix = p.x + d * curr.nx; iy = p.y + d * curr.ny; } else { const u = ((q1x - q0x) * curr.ty - (q1y - q0y) * curr.tx) / denom; ix = q0x + u * prev.tx; iy = q0y + u * prev.ty; } let dx = ix - p.x, dy = iy - p.y; const shift = Math.hypot(dx, dy); if (shift > miterLimit * d) { dx *= (miterLimit * d) / shift; dy *= (miterLimit * d) / shift; } return { x: Number((p.x + dx).toFixed(4)), y: Number((p.y + dy).toFixed(4)) }; }); } 

Checking whether the inset polygon flips sign (Math.sign(signedPolygonArea(insetPts)) !== orientation) also gives you an instant sliver detector: if a segmented photo region collapses after a 0.45 mm foil inset, that piece is physically too tiny to wrap in copper tape and should be merged into its neighbor.

Bug 3: Flagging Concave Reflex Angles (> 195°) Before Glass Snaps

A carbide glass cutter does not saw through glass. It scores a shallow surface fissure, and running pliers bend the sheet so a tension fracture races from one edge of the sheet to the other.

Convex corners (< 180°) and very gentle curves (180° to 195°) can be scored in progressive relief arcs and nibbled clean with grozing pliers. Once an interior reflex angle passes 195° (and especially past 225°, like an inside L-corner), a hand score wants to run straight out through the waist of the piece:

export function findReflexFractureVertices(pts, reflexThresholdDeg = 195) { const orientation = signedPolygonArea(pts) >= 0 ? 1 : -1; const n = pts.length; const flagged = []; for (let i = 0; i < n; i++) { const prev = pts[(i - 1 + n) % n]; const curr = pts[i]; const next = pts[(i + 1) % n]; const ax = prev.x - curr.x, ay = prev.y - curr.y; const bx = next.x - curr.x, by = next.y - curr.y; const turn = orientation * (bx * ay - by * ax); const dot = ax * bx + ay * by; let rad = Math.atan2(turn, dot); if (rad <= 0) rad += 2 * Math.PI; const angleDeg = (rad * 180) / Math.PI; if (angleDeg > reflexThresholdDeg) { flagged.push({ index: i, x: curr.x, y: curr.y, interiorAngleDeg: Number(angleDeg.toFixed(1)), tool: angleDeg > 225 ? "ring-saw-or-split-seam" : "diamond-grinder-relief", }); } } return flagged; } 

In glass-geometry.mjs, we pair this vertex check with an inward bisector ray-cast from each reflex corner across the polygon interior to measure the exact glass bridge throat width behind the notch. Highlighting > 195° pockets in amber and > 225° deep notches in red lets makers add a quick relief seam in two clicks rather than wasting an $18/sq ft sheet of Wissmach or Bullseye glass.

Bug 4: True 96-DPI Inch SVGs, Hanging Seams & Material Takeoffs

Two final geometry details separate a toy canvas export from a shop-ready pattern:

Locking 1:1 Physical Inches in the SVG Root

Exporting <svg width="768" height="960"> without physical units leaves Inkscape, Adobe Reader, LightBurn, and Cricut Design Space guessing whether 1 unit equals 1/72", 1/90", or 1/96". Under the CSS Values and SVG 2 specification, 1in === 96px user units:

export function buildTrueScaleSvgOpenTag(widthInches, heightInches, dpi = 96) { const vbW = Number((widthInches * dpi).toFixed(4)); const vbH = Number((heightInches * dpi).toFixed(4)); return `<svg xmlns="http://www.w3.org/2000/svg" width="${widthInches}in" height="${heightInches}in" viewBox="0 0 ${vbW} ${vbH}">`; } 

When a window panel exceeds home paper size (say 16" x 20" on 8.5" x 11" US Letter with 0.5" unprintable margins), printable = 7.5" x 10". Subtracting a 0.375" (3/8") glue-and-crosshair registration overlap gives a tile step of 7.125" x 9.625", slicing the cartoon cleanly across a 3 x 3 grid of shifted viewBox windows with zero printer scaling drift.

Suncatcher Jump-Ring Seams & Double-Sided Foil Math

If you solder hanging jump rings onto the outer copper foil border at the top of a glass piece, window heat softens the acrylic tape adhesive and peels the foil off the glass edge within months. In our suncatcher stained glass pattern maker, we scan the deduplicated half-edge graph for upper-crown interior solder seams (isInteriorSeam === true) straddling the horizontal center of mass so wire tails embed directly into structural multi-piece joints.

That same half-edge graph also makes material estimation exact: because every interior seam has two neighboring glass edges wrapped in copper foil while the outer border is wrapped once, total foil footage is (2 * interiorSeamInches + outerPerimeterInches) * 1.08 / 12 (with 8% overlap allowance), which powers the sheet glass, foil roll, and 60/40 solder weight formulas in our stained glass cost calculator.

Try the Open-Source Solver or Run Tests Locally

All four solvers (extractSharedHalfEdgeGraph, computeKerfInsetPolygon, detectConcaveAngles, computeTiledPrintPages, plus suncatcher seam and foil/solder takeoff helpers) are MIT-licensed with zero dependencies:

If you have ever fought polygon offset spikes, SVG DPI mismatches across laser/vinyl software, or topological seam tracing on pixel grids, grab glass-geometry.mjs and test it on your worst concave polygons.

原文:https://www.a8q9.cn/en/article/generating-cut-ready-stained-glass-svgs-in-pure-browser-js-shared-half-edges-cop-da5d21.html

相关文章