Communitygithub.com

svg-to-canvas-replica

Zero-error SVG to Canvas replica (A4 print-grade): perfectly reproduces coordinates, text, and styles from A4 SVG design drafts/engineering drawings onto Canvas with <0.001px error. Ideal for print proofing, design restoration, and report export.

What is svg-to-canvas-replica?

This skill provides a pure frontend, zero-dependency Canvas 2D pipeline that faithfully replicates any A4 SVG template (e.g., homework sheets, calligraphy paper, tables) onto a Canvas surface. It preserves every coordinate, line, text, and image with sub-pixel precision — not as a screenshot, but as a fully vectorized, re-editable structure. The core process involves parsing SVG <style> blocks for dynamic class-based styling, extracting elements like rect, line, polygon, text, and image while keeping coordinates in SVG units, then rendering them onto a fixed 1240x1754px Canvas (150dpi) using a unified scaling factor. It supports school/institution template variants, automatic page number detection, and includes a self-test script to verify coordinate conversion accuracy. The skill complements other tools in the 'Canvas Toolchain' for drawing grids, exporting multi-page PDFs, and visual verification workflows.

Works with~Claude Code~Codex CLI~Cursor
npx skills add shuangying0001-beep/svg-to-canvas-replica

Ask in your favorite AI

Open a new chat with this agent skill pre-loaded.

Documentation

SVG to Canvas Precision Replica Pipeline

Teaching Tool · Utility module. Pure frontend Canvas 2D, zero dependencies.

What This Is (For Humans)

Do you have a premade paper template SVG (e.g., exercise sheets, calligraphy paper, tables) and want to turn it into a canvas that you can freely edit text, zoom, and export as PDF inside a mini-program or web page? This skill moves every coordinate, line, text, and image from the SVG onto a Canvas with zero error — not a screenshot, but a vectorized, re-editable replica. School/institution template variants can be toggled with one click. Works for replicating any paper template.

  • Includes selftest.js: Uses a stub ctx to verify coordinate conversion is correct. Only trust it if it reports PASS.

When to Use

  • "Replicate this SVG template onto Canvas" / "Draw this SVG onto a canvas"
  • Need pixel-perfect restoration of a paper template (coordinates, line styles, font sizes consistent)
  • Template has school version and institution version styles to switch between

Coordinate System Conversion (AI Must Read)

Coordinate SystemDimensionsRelationship
SVG viewBox21000 × 297001 unit = 0.01mm
Physical210 × 297 mmA4
Canvas px1240 × 1754150dpi
var SVG_TO_PX = 0.0590476;   // SVG unit → Canvas px (use this for daily work)
// Keep element coordinates in SVG units during parsing; multiply by SVG_TO_PX at render time

Data Extraction Process

  1. Read SVG text → parse <style> dynamically for classes → {stroke,strokeWidth,dashArray} / fill / {fontSize,fontFamily,fontWeight}
  2. Parse <rect>, <line>, <polygon>, <text>, <image> — keep coordinates in SVG units (do not convert yet)
  3. School/Institution toggle: different row counts (rows / rowsInst), core drawing logic shared
  4. At render time, renderElements(ctx, elements) multiplies each coordinate by SVG_TO_PX

Core Function Signatures (For AI to Call Directly)

// Parse SVG text → { source, totalElements, elements:[{type,x,y,w,h,stroke,fill,classes,...}] }
SvgToElements.parseSVG(svgText, sourceName, imgBase)

// Replica render: automatically *SVG_TO_PX; for images, caller must provide drawImage load logic
Replica.renderElements(ctx, elements, { scale?, drawImage? })

// Page number detection: class contains 'footer-text' and text is purely numeric → returns that element (for drawAll to substitute with page number)
Replica.detectPageNo(elements)   // -> element | null

// Template configuration JSON structure (based on SVG measurements)
// { name, grid:{ cellW, cellH, cols, rows, rowsInst, startX, startY },
//   features:{ errorRow, pinyin, correctionCol },
//   branding:{ logo:{x,y,w,h}, qr:{x,y,w,h}, slogan } }

Anti-Patterns (Avoid)

  • ❌ Manually calculating coordinates (error-prone): Always multiply by SVG_TO_PX; zero manual deduction.
  • ❌ Losing class styles after replica: <style> must be dynamically parsed; hardcode no colors.
  • ❌ Drawing institution version with school version row count: Before rendering, select rowsInst based on isInstitution.
  • ❌ Directly dumping images: For <image>, the caller must load the image from defaultSrc before using drawImage.

Self-Test

node references/selftest.js   # Verifies parsing/coordinate conversion/page detection/replica coordinates; only deliver if PASS

Reference Files

  • references/svg-to-elements.js — SVG parser module (UMD)
  • references/replica.js — Canvas replica render + page detection (UMD)
  • references/selftest.js — Node self-test (stub ctx verifies coordinate conversion)

Notes

  • Element coordinates are in SVG units; render scales uniformly; Canvas internal size is fixed at 1240×1754.
  • Complements canvas-grid-engine (which "draws" new grids): This skill handles "replicating" existing templates.

Teaching Tool Canvas Toolchain (Use in Combination)

This skill is part of the Teaching Tool · Canvas Toolchain, with four components covering a complete loop of "Draw → Replicate → Export → Verify":

  • Canvas Learning Paper Grid Engine (Draw): 13 educational grids + Chinese character centering + pinyin annotation, generates mi-zi-ge/tian-zi-ge character sheets.
  • SVG to Canvas Replica Engine (Replicate): Reproduces existing paper template SVGs onto editable, printable Canvas with zero error.
  • Canvas Multi-Page PDF Export (Export): Combines multiple Canvas pages into a single standard A4 PDF for direct printing.
  • Mini-Program Canvas Verification Workflow (Verify): Local preview + screenshot visual regression, eliminates misaligned grids and skewed text.

See the full solution and demo at the "Teaching Tool Canvas Toolchain Landing Page" (link to be added upon publication).

Related Skills