anycoder-c9fbd85a / index.html
allisongattone's picture
Upload folder using huggingface_hub
baa6e0e verified
Raw History Blame Contribute Delete
49.3 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CutForge Studio β€” Raster to SVG Converter</title> <script src="https://cdn.tailwindcss.com"></script> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght@0,9..144,300;0,9..144,400;0,9..144,500;0,9..144,600;0,9..144,700;1,9..144,400&family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet"> <script> tailwind.config = { theme: { extend: { colors: { bone: '#f5f1ea', ink: '#1a1815', 'forest-teal': '#0a6e54', 'saffron': '#f4c542', 'warm-gray': '#e8e2d9', 'soft-ink': '#3d3832', }, fontFamily: { 'heading': ['Fraunces', 'serif'], 'body': ['Inter', 'sans-serif'], } } } } </script> <style> /* ============================================ CUTFORGE STUDIO β€” CUSTOM STYLES ============================================ Modern CSS features used throughout: - CSS Custom Properties (variables) - CSS Grid with named areas - backdrop-filter for glass effects - scroll-driven animations (where supported) - container queries for component-level responsiveness ============================================ */ :root { --bone: #f5f1ea; --ink: #1a1815; --forest-teal: #0a6e54; --saffron: #f4c542; --warm-gray: #e8e2d9; --checker-light: #ffffff; --checker-dark: #e0d8cc; --checker-size: 16px; } * { margin: 0; padding: 0; box-sizing: border-box; } html { scroll-behavior: smooth; } body { font-family: 'Inter', sans-serif; background: var(--bone); color: var(--ink); min-height: 100vh; overflow-x: hidden; } /* ============================================ TYPOGRAPHY β€” Fraunces for display, Inter for UI ============================================ */ .font-heading { font-family: 'Fraunces', serif; font-optical-sizing: auto; } .font-body { font-family: 'Inter', sans-serif; } /* ============================================ CHECKERBOARD BACKGROUND β€” Classic transparency pattern Used for the main preview stage to show alpha channels ============================================ */ .checkerboard { background-image: repeating-conic-gradient( var(--checker-dark) 0% 25%, var(--checker-light) 0% 50% ); background-size: var(--checker-size) var(--checker-size); } /* ============================================ GLASS MORPHISM β€” For floating panels and overlays Uses backdrop-filter for that frosted glass look ============================================ */ .glass { background: rgba(245, 241, 234, 0.85); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); border: 1px solid rgba(232, 226, 217, 0.6); } .glass-dark { background: rgba(26, 24, 21, 0.9); backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px); } /* ============================================ CUSTOM RANGE SLIDER β€” Styled for our palette Modern CSS with custom track and thumb styling ============================================ */ input[type="range"] { -webkit-appearance: none; appearance: none; width: 100%; height: 6px; border-radius: 3px; background: var(--warm-gray); outline: none; cursor: pointer; transition: all 0.2s ease; } input[type="range"]::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 20px; height: 20px; border-radius: 50%; background: var(--forest-teal); border: 3px solid var(--bone); box-shadow: 0 2px 8px rgba(10, 110, 84, 0.3); cursor: pointer; transition: all 0.2s ease; } input[type="range"]::-webkit-slider-thumb:hover { transform: scale(1.15); box-shadow: 0 4px 16px rgba(10, 110, 84, 0.4); } input[type="range"]::-moz-range-thumb { width: 20px; height: 20px; border-radius: 50%; background: var(--forest-teal); border: 3px solid var(--bone); box-shadow: 0 2px 8px rgba(10, 110, 84, 0.3); cursor: pointer; } /* ============================================ ANIMATIONS β€” Smooth state transitions ============================================ */ @keyframes fadeIn { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } } @keyframes slideInLeft { from { opacity: 0; transform: translateX(-20px); } to { opacity: 1; transform: translateX(0); } } @keyframes pulse-glow { 0%, 100% { box-shadow: 0 0 0 0 rgba(10, 110, 84, 0.3); } 50% { box-shadow: 0 0 0 8px rgba(10, 110, 84, 0); } } @keyframes spin-slow { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } @keyframes dash { to { stroke-dashoffset: 0; } } .animate-fade-in { animation: fadeIn 0.5s ease-out forwards; } .animate-slide-in { animation: slideInLeft 0.6s ease-out forwards; } .animate-pulse-glow { animation: pulse-glow 2s ease-in-out infinite; } .animate-spin-slow { animation: spin-slow 3s linear infinite; } /* ============================================ STATE INDICATOR DOTS β€” Pulsing status lights ============================================ */ .status-dot { width: 8px; height: 8px; border-radius: 50%; transition: all 0.4s ease; } .status-idle { background: var(--warm-gray); } .status-uploading { background: var(--saffron); animation: pulse-glow 1s ease-in-out infinite; } .status-masking { background: var(--saffron); animation: pulse-glow 0.8s ease-in-out infinite; } .status-vectorizing { background: var(--forest-teal); animation: pulse-glow 0.6s ease-in-out infinite; } .status-ready { background: var(--forest-teal); } /* ============================================ DROP ZONE β€” Interactive upload area Uses CSS transitions for hover states ============================================ */ .drop-zone { border: 2px dashed var(--warm-gray); transition: all 0.3s ease; } .drop-zone:hover, .drop-zone.drag-active { border-color: var(--forest-teal); background: rgba(10, 110, 84, 0.05); } .drop-zone.drag-active { transform: scale(1.02); } /* ============================================ TOOLTIP β€” Custom hint system ============================================ */ .tooltip { position: relative; } .tooltip::after { content: attr(data-tip); position: absolute; bottom: 100%; left: 50%; transform: translateX(-50%) translateY(-8px); padding: 6px 12px; background: var(--ink); color: var(--bone); font-size: 12px; border-radius: 6px; white-space: nowrap; opacity: 0; pointer-events: none; transition: all 0.2s ease; } .tooltip:hover::after { opacity: 1; transform: translateX(-50%) translateY(-4px); } /* ============================================ SCROLLBAR β€” Custom styled for consistency ============================================ */ ::-webkit-scrollbar { width: 8px; height: 8px; } ::-webkit-scrollbar-track { background: var(--bone); } ::-webkit-scrollbar-thumb { background: var(--warm-gray); border-radius: 4px; } ::-webkit-scrollbar-thumb:hover { background: var(--soft-ink); } /* ============================================ PROGRESS RING β€” SVG-based circular indicator ============================================ */ .progress-ring { transform: rotate(-90deg); } .progress-ring-circle { transition: stroke-dashoffset 0.35s ease; transform-origin: 50% 50%; } /* ============================================ COLOR SWATCH β€” For palette preview ============================================ */ .color-swatch { width: 24px; height: 24px; border-radius: 6px; border: 2px solid var(--bone); box-shadow: 0 1px 4px rgba(0,0,0,0.1); transition: transform 0.2s ease; } .color-swatch:hover { transform: scale(1.2); } /* ============================================ LOADING SKELETON β€” Shimmer effect ============================================ */ @keyframes shimmer { 0% { background-position: -200% 0; } 100% { background-position: 200% 0; } } .skeleton { background: linear-gradient(90deg, var(--warm-gray) 25%, #f0ece4 50%, var(--warm-gray) 75%); background-size: 200% 100%; animation: shimmer 1.5s ease-in-out infinite; } /* ============================================ SVG PREVIEW β€” Container for the output ============================================ */ .svg-preview { max-width: 100%; max-height: 100%; filter: drop-shadow(0 4px 12px rgba(0,0,0,0.08)); } /* ============================================ CONTAINER QUERY β€” Modern responsive component ============================================ */ .cq-container { container-type: inline-size; container-name: preview; } @container preview (max-width: 400px) { .cq-responsive { font-size: 14px; } } /* ============================================ SELECTION RING β€” For interactive elements ============================================ */ .select-ring { position: relative; } .select-ring::before { content: ''; position: absolute; inset: -4px; border-radius: inherit; border: 2px solid var(--saffron); opacity: 0; transition: opacity 0.2s ease; pointer-events: none; } .select-ring:focus::before, .select-ring.active::before { opacity: 1; } /* ============================================ MASK BRUSH CURSOR β€” Visual feedback for masking ============================================ */ .mask-cursor { cursor: crosshair; } /* ============================================ ANYCODER LINK β€” Required attribution ============================================ */ .anycoder-link { color: var(--forest-teal); text-decoration: none; font-weight: 500; transition: all 0.2s ease; position: relative; } .anycoder-link::after { content: ''; position: absolute; bottom: -2px; left: 0; width: 0; height: 2px; background: var(--forest-teal); transition: width 0.3s ease; } .anycoder-link:hover::after { width: 100%; } .anycoder-link:hover { color: var(--forest-teal); } /* ============================================ BADGE β€” Status labels ============================================ */ .badge { display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 500; letter-spacing: 0.02em; } .badge-teal { background: rgba(10, 110, 84, 0.1); color: var(--forest-teal); } .badge-saffron { background: rgba(244, 197, 66, 0.15); color: #9a7b1a; } /* ============================================ DIVIDER β€” Elegant separator ============================================ */ .divider { height: 1px; background: linear-gradient(90deg, transparent, var(--warm-gray), transparent); } /* ============================================ HOVER LIFT β€” Subtle elevation on interaction ============================================ */ .hover-lift { transition: transform 0.3s ease, box-shadow 0.3s ease; } .hover-lift:hover { transform: translateY(-2px); box-shadow: 0 8px 24px rgba(0,0,0,0.08); } /* ============================================ FOCUS STYLES β€” Accessible keyboard navigation ============================================ */ *:focus-visible { outline: 2px solid var(--saffron); outline-offset: 2px; border-radius: 4px; } /* ============================================ NUMBER INPUT β€” Styled spinners ============================================ */ input[type="number"]::-webkit-inner-spin-button, input[type="number"]::-webkit-outer-spin-button { opacity: 1; height: 20px; cursor: pointer; } /* ============================================ PREVIEW ZOOM CONTROLS ============================================ */ .zoom-control { width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; border-radius: 8px; background: var(--bone); border: 1px solid var(--warm-gray); color: var(--soft-ink); cursor: pointer; transition: all 0.2s ease; } .zoom-control:hover { background: var(--forest-teal); color: white; border-color: var(--forest-teal); } /* ============================================ PATH VISUALIZATION β€” For the vectorization preview ============================================ */ .path-preview line, .path-preview path { stroke: var(--forest-teal); stroke-width: 1; fill: none; opacity: 0.6; } /* ============================================ COMPARISON SLIDER β€” Before/after reveal ============================================ */ .compare-slider { position: relative; overflow: hidden; } .compare-slider .after-layer { position: absolute; top: 0; left: 0; width: 50%; height: 100%; overflow: hidden; border-right: 2px solid var(--saffron); } .compare-handle { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 40px; height: 40px; background: var(--saffron); border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: ew-resize; box-shadow: 0 4px 12px rgba(0,0,0,0.2); } /* ============================================ LAYER PANEL β€” For multi-color output ============================================ */ .layer-item { display: flex; align-items: center; gap: 12px; padding: 10px 14px; border-radius: 10px; transition: all 0.2s ease; cursor: pointer; } .layer-item:hover { background: rgba(10, 110, 84, 0.05); } .layer-item.active { background: rgba(10, 110, 84, 0.1); border: 1px solid rgba(10, 110, 84, 0.2); } .layer-visibility { width: 18px; height: 18px; border-radius: 4px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.2s ease; } /* ============================================ FILE TYPE ICONS ============================================ */ .file-icon { width: 48px; height: 48px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 20px; font-weight: 600; } .file-icon-heic { background: rgba(244, 197, 66, 0.15); color: #9a7b1a; } .file-icon-image { background: rgba(10, 110, 84, 0.1); color: var(--forest-teal); } /* ============================================ RESPONSIVE GRID β€” 12-column asymmetric layout Left rail: cols 1-3, Main stage: cols 4-12 ============================================ */ .app-grid { display: grid; grid-template-columns: minmax(280px, 1fr) 3fr; min-height: 100vh; } @media (max-width: 1024px) { .app-grid { grid-template-columns: 1fr; grid-template-rows: auto 1fr; } } /* ============================================ STICKY LEFT RAIL ============================================ */ .left-rail { position: sticky; top: 0; height: 100vh; overflow-y: auto; } @media (max-width: 1024px) { .left-rail { position: relative; height: auto; max-height: 50vh; } } /* ============================================ MAIN STAGE β€” Full viewport height with scroll ============================================ */ .main-stage { min-height: 100vh; overflow-y: auto; } /* ============================================ CANVAS DISPLAY β€” Pixel-perfect rendering ============================================ */ canvas { image-rendering: -moz-crisp-edges; image-rendering: -webkit-crisp-edges; image-rendering: pixelated; image-rendering: crisp-edges; } /* ============================================ TOAST NOTIFICATION β€” Temporary feedback ============================================ */ .toast { position: fixed; bottom: 24px; right: 24px; padding: 14px 24px; background: var(--ink); color: var(--bone); border-radius: 12px; font-size: 14px; font-weight: 500; box-shadow: 0 8px 32px rgba(0,0,0,0.2); transform: translateY(100px); opacity: 0; transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); z-index: 1000; } .toast.show { transform: translateY(0); opacity: 1; } /* ============================================ KEYBOARD SHORTCUT BADGE ============================================ */ .kbd { display: inline-flex; align-items: center; justify-content: center; min-width: 24px; height: 24px; padding: 0 6px; background: var(--warm-gray); border-radius: 6px; font-size: 12px; font-weight: 600; font-family: 'Inter', monospace; color: var(--soft-ink); border-bottom: 2px solid #d4cfc6; } /* ============================================ PRESET BUTTONS β€” Quick setting selectors ============================================ */ .preset-btn { padding: 8px 16px; border-radius: 8px; font-size: 13px; font-weight: 500; border: 1.5px solid var(--warm-gray); background: transparent; color: var(--soft-ink); cursor: pointer; transition: all 0.2s ease; } .preset-btn:hover { border-color: var(--forest-teal); color: var(--forest-teal); } .preset-btn.active { background: var(--forest-teal); border-color: var(--forest-teal); color: white; } /* ============================================ TOGGLE SWITCH β€” Modern checkbox alternative ============================================ */ .toggle { position: relative; width: 44px; height: 24px; border-radius: 12px; background: var(--warm-gray); cursor: pointer; transition: background 0.3s ease; } .toggle::after { content: ''; position: absolute; top: 2px; left: 2px; width: 20px; height: 20px; border-radius: 50%; background: white; box-shadow: 0 1px 4px rgba(0,0,0,0.15); transition: transform 0.3s ease; } .toggle.active { background: var(--forest-teal); } .toggle.active::after { transform: translateX(20px); } /* ============================================ INFO PANEL β€” Expandable help sections ============================================ */ .info-panel { max-height: 0; overflow: hidden; transition: max-height 0.3s ease; } .info-panel.expanded { max-height: 200px; } /* ============================================ STAT CARD β€” Metrics display ============================================ */ .stat-card { padding: 16px; border-radius: 12px; background: white; border: 1px solid var(--warm-gray); } .stat-value { font-family: 'Fraunces', serif; font-size: 28px; font-weight: 600; color: var(--forest-teal); line-height: 1; } .stat-label { font-size: 12px; font-weight: 500; color: var(--soft-ink); text-transform: uppercase; letter-spacing: 0.05em; margin-top: 4px; } /* ============================================ HISTORY THUMBNAIL β€” Previous conversions ============================================ */ .history-thumb { width: 64px; height: 64px; border-radius: 10px; object-fit: cover; border: 2px solid var(--warm-gray); transition: all 0.2s ease; cursor: pointer; } .history-thumb:hover { border-color: var(--forest-teal); transform: scale(1.05); } </style> </head> <body> <div id="app"> <!-- ============================================ APPLICATION ROOT β€” React will mount here Fallback content shown while loading ============================================ --> <div style="display:flex;align-items:center;justify-content:center;height:100vh;flex-direction:column;gap:16px;"> <div style="width:48px;height:48px;border:3px solid var(--warm-gray);border-top-color:var(--forest-teal);border-radius:50%;animation:spin-slow 1s linear infinite;"></div> <p style="font-family:'Inter',sans-serif;color:var(--soft-ink);font-size:14px;">Loading CutForge Studio...</p> </div> </div> <!-- ============================================ REACT 18 β€” Loaded from CDN for single-file deployment Using production build for performance ============================================ --> <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> <!-- ============================================ LUCIDE ICONS β€” SVG icon library Loaded as script for global access ============================================ --> <script src="https://unpkg.com/lucide@latest/dist/umd/lucide.min.js"></script> <script type="text/babel"> // ============================================ // CUTFORGE STUDIO β€” COMPLETE REACT APPLICATION // Single-file implementation with all features // ============================================ const { useState, useReducer, useCallback, useRef, useEffect, useMemo } = React; // ============================================ // STATE MACHINE β€” Central reducer architecture // Five distinct states: IDLE, UPLOADING, MASKING, VECTORIZING, READY // ============================================ const AppState = { IDLE: 'IDLE', UPLOADING: 'UPLOADING', MASKING: 'MASKING', VECTORIZING: 'VECTORIZING', READY: 'READY' }; // ============================================ // ACTION TYPES β€” All state mutations flow through here // ============================================ const ActionTypes = { SET_STATE: 'SET_STATE', SET_FILE: 'SET_FILE', SET_IMAGE_DATA: 'SET_IMAGE_DATA', SET_MASK: 'SET_MASK', SET_PARAMS: 'SET_PARAMS', SET_SVG: 'SET_SVG', SET_PROGRESS: 'SET_PROGRESS', ADD_HISTORY: 'ADD_HISTORY', RESET: 'RESET', SET_ERROR: 'SET_ERROR' }; // ============================================ // INITIAL STATE β€” Default configuration // ============================================ const initialState = { appState: AppState.IDLE, file: null, fileName: '', imageData: null, // ImageData from canvas originalImageData: null, // Unmasked original maskImageData: null, // Alpha mask from background removal params: { tolerance: 30, // Manhattan distance threshold for alpha-keying pathSimplification: 2, // Douglas-Peucker epsilon colorCount: 8, // K-means clusters for posterization smoothing: 1, // Gaussian blur passes invertMask: false, // Keep background instead of foreground cornerThreshold: 45 // Angle for corner detection in paths }, svg: null, // Generated SVG string svgSanitized: null, // Post-processed for Cricut/Silhouette progress: 0, // 0-100 for long operations history: [], // Previous conversions error: null, // Error message if something fails zoom: 100, // Preview zoom percentage showComparison: false, // Before/after slider selectedLayer: -1, // Active color layer layers: [] // Extracted color layers }; // ============================================ // REDUCER β€” Pure state transformation function // All state changes centralized for predictability // ============================================ function appReducer(state, action) { switch (action.type) { case ActionTypes.SET_STATE: return { ...state, appState: action.payload, error: null }; case ActionTypes.SET_FILE: return { ...state, file: action.payload.file, fileName: action.payload.fileName, appState: AppState.UPLOADING }; case ActionTypes.SET_IMAGE_DATA: return { ...state, imageData: action.payload, originalImageData: action.payload, appState: AppState.MASKING, progress: 0 }; case ActionTypes.SET_MASK: return { ...state, maskImageData: action.payload, appState: AppState.VECTORIZING }; case ActionTypes.SET_PARAMS: return { ...state, params: { ...state.params, ...action.payload } }; case ActionTypes.SET_SVG: return { ...state, svg: action.payload.svg, svgSanitized: action.payload.sanitized, layers: action.payload.layers || [], appState: AppState.READY, progress: 100 }; case ActionTypes.SET_PROGRESS: return { ...state, progress: action.payload }; case ActionTypes.ADD_HISTORY: return { ...state, history: [action.payload, ...state.history].slice(0, 10) }; case ActionTypes.RESET: return { ...initialState, history: state.history // Preserve history across resets }; case ActionTypes.SET_ERROR: return { ...state, error: action.payload, appState: AppState.IDLE }; default: return state; } } // ============================================ // UTILITY: MANHATTAN DISTANCE β€” Background removal core // |R1-R2| + |G1-G2| + |B1-B2| β€” Faster than Euclidean, no sqrt // ============================================ function manhattanDistance(r1, g1, b1, r2, g2, b2) { return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2); } // ============================================ // UTILITY: HEIC MOCK β€” Pattern for heic2any integration // In production, replace with: import heic2any from 'heic2any' // This mock converts HEIC to JPEG for browser processing // ============================================ async function mockHeicToAny(blob, options = {}) { // MOCK IMPLEMENTATION β€” Replace with actual heic2any library // In production: return await heic2any({ blob, toType: 'image/jpeg', quality: 0.92 }); console.log('HEIC conversion mock:', { blob, options }); // Simulate conversion delay await new Promise(r => setTimeout(r, 800)); // Return as-is for demo (browser would fail, but mock allows flow) return blob; } // ============================================ // UTILITY: LOAD IMAGE FROM FILE β€” Returns Promise<Image> // Handles HEIC via mock conversion, all others natively // ============================================ function loadImageFromFile(file) { return new Promise(async (resolve, reject) => { try { let blob = file; let fileName = file.name; // ============================================ // HEIC DETECTION β€” Check extension and MIME type // Apple devices often use .heic, .heif extensions // ============================================ const isHeic = /\.(heic|heif)$/i.test(fileName) || file.type === 'image/heic' || file.type === 'image/heif'; if (isHeic) { blob = await mockHeicToAny(file, { toType: 'image/jpeg', quality: 0.92 }); } const url = URL.createObjectURL(blob); const img = new Image(); img.onload = () => { URL.revokeObjectURL(url); resolve(img); }; img.onerror = () => { URL.revokeObjectURL(url); reject(new Error('Failed to load image')); }; img.src = url; } catch (err) { reject(err); } }); } // ============================================ // CORE: BACKGROUND REMOVAL β€” Manhattan Distance Alpha-Keying // Samples corner pixels as "background color", keys everything similar // ============================================ function removeBackground(imageData, tolerance, invert = false) { const { width, height, data } = imageData; const output = new ImageData(width, height); const outData = output.data; // ============================================ // SAMPLE BACKGROUND β€” Average of 4 corner pixels // Assumes subject is centered, background at edges // ============================================ const corners = [ { x: 2, y: 2 }, // Top-left { x: width - 3, y: 2 }, // Top-right { x: 2, y: height - 3 }, // Bottom-left { x: width - 3, y: height - 3 } // Bottom-right ]; let bgR = 0, bgG = 0, bgB = 0; corners.forEach(c => { const i = (c.y * width + c.x) * 4; bgR += data[i]; bgG += data[i + 1]; bgB += data[i + 2]; }); bgR = Math.round(bgR / 4); bgG = Math.round(bgG / 4); bgB = Math.round(bgB / 4); // ============================================ // PIXEL-LEVEL KEYING β€” Per-pixel Manhattan distance // Pixels within tolerance become transparent // ============================================ for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const i = (y * width + x) * 4; const r = data[i]; const g = data[i + 1]; const b = data[i + 2]; const a = data[i + 3]; const dist = manhattanDistance(r, g, b, bgR, bgG, bgB); const isBackground = dist <= tolerance; // Apply inversion if requested (keep bg, remove fg) const makeTransparent = invert ? !isBackground : isBackground; outData[i] = r; outData[i + 1] = g; outData[i + 2] = b; outData[i + 3] = makeTransparent ? 0 : a; } } return output; } // ============================================ // CORE: COLOR QUANTIZATION β€” K-Means clustering for posterization // Reduces image to N colors for clean vector output // ============================================ function quantizeColors(imageData, colorCount) { const { width, height, data } = imageData; const pixels = []; // Collect non-transparent pixels for (let i = 0; i < data.length; i += 4) { if (data[i + 3] > 128) { pixels.push([data[i], data[i + 1], data[i + 2]]); } } if (pixels.length === 0) return imageData; // ============================================ // K-MEANS++ INITIALIZATION β€” Smart centroid selection // First centroid random, subsequent weighted by distance // ============================================ let centroids = []; const used = new Set(); // First centroid: random let idx = Math.floor(Math.random() * pixels.length); centroids.push([...pixels[idx]]); used.add(idx); // Remaining centroids: weighted by distance to nearest while (centroids.length < colorCount) { const distances = pixels.map(p => { let minDist = Infinity; for (const c of centroids) { const d = manhattanDistance(p[0], p[1], p[2], c[0], c[1], c[2]); if (d < minDist) minDist = d; } return minDist * minDist; // Square for weighting }); const total = distances.reduce((a, b) => a + b, 0); let threshold = Math.random() * total; let cumulative = 0; let selected = 0; for (let i = 0; i < distances.length; i++) { cumulative += distances[i]; if (cumulative >= threshold) { selected = i; break; } } if (!used.has(selected)) { centroids.push([...pixels[selected]]); used.add(selected); } } // ============================================ // K-MEANS ITERATION β€” Lloyd's algorithm // Converge centroids to cluster means // ============================================ const MAX_ITERATIONS = 10; const assignments = new Array(pixels.length); for (let iter = 0; iter < MAX_ITERATIONS; iter++) { // Assign pixels to nearest centroid let changed = false; for (let i = 0; i < pixels.length; i++) { let bestDist = Infinity; let bestCentroid = 0; for (let c = 0; c < centroids.length; c++) { const d = manhattanDistance( pixels[i][0], pixels[i][1], pixels[i][2], centroids[c][0], centroids[c][1], centroids[c][2] ); if (d < bestDist) { bestDist = d; bestCentroid = c; } } if (assignments[i] !== bestCentroid) { assignments[i] = bestCentroid; changed = true; } } if (!changed) break; // Recompute centroids as means of assigned pixels const sums = centroids.map(() => [0, 0, 0, 0]); for (let i = 0; i < pixels.length; i++) { const c = assignments[i]; sums[c][0] += pixels[i][0]; sums[c][1] += pixels[i][1]; sums[c][2] += pixels[i][2]; sums[c][3]++; } for (let c = 0; c < centroids.length; c++) { if (sums[c][3] > 0) { centroids[c] = [ Math.round(sums[c][0] / sums[c][3]), Math.round(sums[c][1] / sums[c][3]), Math.round(sums[c][2] / sums[c][3]) ]; } } } // ============================================ // APPLY QUANTIZATION β€” Map each pixel to nearest centroid // Build color layer information for multi-color SVG // ============================================ const output = new ImageData(width, height); const colorMap = new Map(); // centroid index -> color info centroids.forEach((c, i) => { colorMap.set(i, { r: c[0], g: c[1], b: c[2], hex: `#${c[0].toString(16).padStart(2,'0')}${c[1].toString(16).padStart(2,'0')}${c[2].toString(16).padStart(2,'0')}`, paths: [] }); }); let pixelIdx = 0; for (let i = 0; i < data.length; i += 4) { if (data[i + 3] > 128) { const c = assignments[pixelIdx++]; const color = centroids[c]; output.data[i] = color[0]; output.data[i + 1] = color[1]; output.data[i + 2] = color[2]; output.data[i + 3] = 255; } else { output.data[i + 3] = 0; } } return { imageData: output, centroids, colorMap }; } // ============================================ // CORE: EDGE DETECTION & PATH TRACING β€” Marching Squares variant // Traces boundaries between different colors to generate paths // ============================================ function traceContours(imageData, colorMap, simplification) { const { width, height, data } = imageData; const paths = []; // ============================================ // GRID-BASED CONTOUR TRACING β€” Per-color isolation // Process each color layer separately for clean paths // ============================================ for (const [colorIdx, colorInfo] of colorMap) { const visited = new Set(); const colorPaths = []; // Create binary mask for this color for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const i = (y * width + x) * 4; const key = `${x},${y}`; if (visited.has(key)) continue; // Check if this pixel matches our color const isMatch = data[i] === colorInfo.r && data[i + 1] === colorInfo.g && data[i + 2] === colorInfo.b && data[i + 3] > 128; if (!isMatch) continue; // ============================================ // FLOOD FILL β€” Find connected region of this color // Uses 4-connectivity for cleaner edges // ============================================ const region = []; const queue = [[x, y]]; visited.add(key); while (queue.length > 0) { const [cx, cy] = queue.pop(); region.push([cx, cy]); const neighbors = [[0,-1],[0,1],[-1,0],[1,0]]; for (const [dx, dy] of neighbors) { const nx = cx + dx, ny = cy + dy; if (nx < 0 || nx >= width || ny < 0 || ny >= height) continue; const nKey = `${nx},${ny}`; if (visited.has(nKey)) continue; const ni = (ny * width + nx) * 4; const nMatch = data[ni] === colorInfo.r && data[ni + 1] === colorInfo.g && data[ni + 2] === colorInfo.b && data[ni + 3] > 128; if (nMatch) { visited.add(nKey); queue.push([nx, ny]); } } } // ============================================ // BOUNDARY TRACING β€” Moore-neighbor tracing // Walks the edge of the region to create path // ============================================ if (region.length < 10) continue; // Skip noise const boundary = traceBoundary(region, width, height, data, colorInfo); if (boundary.length > 2) { // ============================================ // DOUGLAS-PEUCKER SIMPLIFICATION β€” Reduce points // Keeps shape fidelity while minimizing path data // ============================================ const simplified = douglasPeucker(boundary, simplification); colorPaths.push({ points: simplified, color: colorInfo.hex, isHole: false }); } } } paths.push(...colorPaths); } return paths; } // ============================================ // HELPER: BOUNDARY TRACING β€” Find edge pixels of region // Uses the region's bounding box and edge detection // ============================================ function traceBoundary(region, width, height, data, colorInfo) { // Create set for O(1) lookup const regionSet = new Set(region.map(([x, y]) => `${x},${y}`)); // Find topmost-leftmost point as start let start = region[0]; for (const [x, y] of region) { if (y < start[1] || (y === start[1] && x < start[0])) { start = [x, y]; } } // Simple boundary: collect edge pixels const boundary = []; const edgeSet = new Set(); for (const [x, y] of region) { const isEdge = [[0,-1],[0,1],[-1,0],[1,0]].some(([dx, dy]) => { const nx =
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CutForge Studio β€” Raster to SVG Converter</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght@0,9..144,300;0,9..144,400;0,9..144,500;0,9..144,600;0,9..144,700;1,9..144,400&family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<script>
tailwind.config = {
theme: {
extend: {
colors: {
bone: '#f5f1ea',
ink: '#1a1815',
'forest-teal': '#0a6e54',
'saffron': '#f4c542',
'warm-gray': '#e8e2d9',
'soft-ink': '#3d3832',
},
fontFamily: {
'heading': ['Fraunces', 'serif'],
'body': ['Inter', 'sans-serif'],
}
}
}
}
</script>
<style>
/* ============================================
CUTFORGE STUDIO β€” CUSTOM STYLES
============================================
Modern CSS features used throughout:
- CSS Custom Properties (variables)
- CSS Grid with named areas
- backdrop-filter for glass effects
- scroll-driven animations (where supported)
- container queries for component-level responsiveness
============================================ */
:root {
--bone: #f5f1ea;
--ink: #1a1815;
--forest-teal: #0a6e54;
--saffron: #f4c542;
--warm-gray: #e8e2d9;
--checker-light: #ffffff;
--checker-dark: #e0d8cc;
--checker-size: 16px;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html {
scroll-behavior: smooth;
}
body {
font-family: 'Inter', sans-serif;
background: var(--bone);
color: var(--ink);
min-height: 100vh;
overflow-x: hidden;
}
/* ============================================
TYPOGRAPHY β€” Fraunces for display, Inter for UI
============================================ */
.font-heading {
font-family: 'Fraunces', serif;
font-optical-sizing: auto;
}
.font-body {
font-family: 'Inter', sans-serif;
}
/* ============================================
CHECKERBOARD BACKGROUND β€” Classic transparency pattern
Used for the main preview stage to show alpha channels
============================================ */
.checkerboard {
background-image:
repeating-conic-gradient(
var(--checker-dark) 0% 25%,
var(--checker-light) 0% 50%
);
background-size: var(--checker-size) var(--checker-size);
}
/* ============================================
GLASS MORPHISM β€” For floating panels and overlays
Uses backdrop-filter for that frosted glass look
============================================ */