CUT PATTERN PROJECTOR

Live ↗ZIP (lokal ausführbar)
Beschreibung

Web-based prototype for projecting SVG cut patterns onto a physical cutting mat through a camera or projector setup. The projection is based on a four-point homography: four corner handles are placed on grid crossings of the mat, and the real width and height of that rectangle are entered in millimetres. The prototype converts the SVG geometry into polylines in millimetres, including paths, arcs, rectangles, circles, ellipses and dashed strokes, and maps them onto the calibrated area. Loaded patterns can be moved, rotated, mirrored and scaled, and their stroke colours can be toggled and recoloured per group. A grid in millimetres is drawn over the projection area, and the calibration and display settings are stored in the browser. The prototype is intended for testing pattern projection, for teaching pattern construction, and as a starting point for further projection tools.

  • Version: v1.0
  • Calibration with four corner handles and real-world width and height in millimetres
  • SVG import by file picker or drag and drop, plus a built-in test pattern
  • Pattern placement with position, rotation, mirroring and scaling
  • Per-colour group visibility and display colour
  • Millimetre grid with adjustable spacing, also shown in projection mode
  • Fullscreen mode and keyboard control for corners and patterns
  • Settings saved in local storage
  • Tech: HTML, CSS, JavaScript, Canvas 2D, SVG DOM, localStorage
  • Requires: modern browser with Canvas 2D and fullscreen support, SVG files, a camera or projector for the physical projection
index.html
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<title>Schnittmuster-Projektion</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
:root{--line:#2c2c2c;--text:#dcdcdc;--dim:#888;--acc:#ff9f0a}
*{box-sizing:border-box}
html,body{margin:0;height:100%;background:#000;color:var(--text);font:12px/1.45 system-ui,-apple-system,"Segoe UI",sans-serif;overflow:hidden}
canvas{position:fixed;inset:0;width:100%;height:100%;display:block;touch-action:none}
#svghost{position:absolute;left:-12000px;top:0;width:1000px;height:1000px;visibility:hidden;pointer-events:none}

#panel{position:fixed;top:0;right:0;bottom:0;width:310px;background:#000;border-left:1px solid var(--line);overflow-y:auto;padding:14px 14px 30px;transition:transform .15s}
#panel.hidden:not(.peek){transform:translateX(100%)}
h1{font-size:11px;letter-spacing:.14em;font-weight:600;margin:0 0 12px;color:#fff}
h2{font-size:10px;letter-spacing:.14em;text-transform:uppercase;color:var(--dim);font-weight:600;margin:20px 0 8px;padding-top:12px;border-top:1px solid var(--line)}
p.hint{color:var(--dim);margin:0 0 8px}
.row{display:flex;gap:6px;align-items:center;margin:6px 0}
.row>label{flex:1;color:#bbb}
.row>span{color:var(--dim);width:22px}
input,select,button{background:#000;color:#eee;border:1px solid #3a3a3a;border-radius:3px;padding:4px 7px;font:inherit}
input[type=number]{width:82px}
input[type=color]{width:34px;height:22px;padding:0;border:1px solid #3a3a3a}
input[type=range]{padding:0;accent-color:#fff;width:130px}
input[type=checkbox]{accent-color:#fff}
button{cursor:pointer}
button:hover,select:hover,input:hover{border-color:#888}
button.on{background:#fff;color:#000;border-color:#fff}
.seg{display:flex}
.seg button{flex:1;border-radius:0;margin-left:-1px}
.seg button:first-child{border-radius:3px 0 0 3px;margin-left:0}
.seg button:last-child{border-radius:0 3px 3px 0}
.seg.mini{flex:none}
.seg.mini button{width:34px;flex:none}
.info{color:var(--dim);font-variant-numeric:tabular-nums;margin-top:6px}
#msg{color:var(--acc);min-height:16px;margin-top:6px}
.item{display:flex;gap:6px;margin:4px 0}
.item button.name{flex:1;text-align:left;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.sw{width:12px;height:12px;border-radius:2px;border:1px solid #555;flex:none}
.grp{display:flex;align-items:center;gap:8px;margin:4px 0;color:#bbb}
.grp .n{flex:1;color:var(--dim)}
kbd{border:1px solid #3a3a3a;border-radius:3px;padding:0 4px;font:inherit;color:#ccc}
.keys{color:var(--dim);line-height:1.9}
</style>
</head>
<body>
<canvas id="cv"></canvas>
<div id="svghost"></div>

<div id="panel">
  <h1>SCHNITTMUSTER · PROJEKTION</h1>
  <div class="row">
    <button id="btnFull" style="flex:1">Vollbild (F)</button>
    <button id="btnHide" style="flex:1">Panel aus (H)</button>
  </div>
  <div class="seg" style="margin-top:8px">
    <button id="mProj">Projektion</button>
    <button id="mCal">Kalibrierung</button>
  </div>

  <div id="secCal">
    <h2>Kalibrierung</h2>
    <p class="hint">Ziehe die vier Eckkreuze auf vier Gitterkreuzungen der Cutting-Mat und trage das echte Maß dieses Rechtecks ein.
      1 = links oben (Nullpunkt), 2 = rechts oben, 3 = rechts unten, 4 = links unten. Je weiter auseinander, desto genauer.
      Feinjustage: Pfeiltasten (Shift = 10 px).</p>
    <div class="row"><label>Breite (1 → 2)</label><input id="refW" type="number" min="10" step="1"><span>mm</span></div>
    <div class="row"><label>Höhe (1 → 4)</label><input id="refH" type="number" min="10" step="1"><span>mm</span></div>
    <div class="row"><label>Aktive Ecke</label>
      <div class="seg mini" id="corner"><button data-i="0">1</button><button data-i="1">2</button><button data-i="2">3</button><button data-i="3">4</button></div>
    </div>
    <div class="row"><label>Raster</label>
      <select id="gridStep"><option value="10">10 mm</option><option value="20">20 mm</option><option value="25">25 mm</option><option value="50">50 mm</option><option value="100">100 mm</option></select>
    </div>
    <div class="row"><button id="resetCorners" style="flex:1">Ecken zurücksetzen</button></div>
    <div id="scaleInfo" class="info"></div>
  </div>

  <h2>Schnittmuster</h2>
  <div class="row">
    <button id="btnLoad" style="flex:1">SVG laden …</button>
    <button id="btnDemo" style="flex:1">Testmuster</button>
  </div>
  <p class="hint" style="margin:4px 0">SVG-Dateien auch per Drag &amp; Drop auf die Fläche.</p>
  <div id="msg"></div>
  <div id="list"></div>

  <div id="props" style="display:none">
    <div class="row"><label>Einheit der SVG</label>
      <select id="pUnit">
        <option value="auto">automatisch</option><option value="mm">mm</option><option value="cm">cm</option>
        <option value="in">Zoll</option><option value="px">px (96 dpi)</option><option value="pt">pt (72 dpi)</option>
      </select>
    </div>
    <div class="row"><label>Mitte X</label><input id="pX" type="number" step="1"><span>mm</span></div>
    <div class="row"><label>Mitte Y</label><input id="pY" type="number" step="1"><span>mm</span></div>
    <div class="row"><label>Drehung</label><input id="pRot" type="number" step="1"><span>°</span></div>
    <div class="row"><label>Skalierung</label><input id="pScale" type="number" step="0.1" min="1"><span>%</span></div>
    <div class="row">
      <label><input id="pMirror" type="checkbox"> Spiegeln</label>
      <button id="pRotM">−90°</button><button id="pRotP">+90°</button><button id="pCenter">Mitte</button>
    </div>
    <div id="pInfo" class="info"></div>
    <div style="margin-top:8px" id="groups"></div>
  </div>

  <h2>Darstellung</h2>
  <div class="row"><label>Linienstärke</label><input id="lineW" type="range" min="0.5" max="6" step="0.5"></div>
  <div class="row"><label><input id="fill" type="checkbox"> Flächen aufhellen</label><input id="fillA" type="range" min="0.05" max="1" step="0.05"></div>
  <div class="row"><label><input id="gridProj" type="checkbox"> Raster auch in Projektion</label></div>

  <h2>Tasten</h2>
  <div class="keys">
    <kbd>H</kbd> Panel ein/aus (am rechten Rand kurz einblendbar)<br>
    <kbd>F</kbd> Vollbild &nbsp; <kbd>C</kbd> Modus wechseln &nbsp; <kbd>G</kbd> Raster<br>
    <kbd>1</kbd>–<kbd>4</kbd> Ecke wählen &nbsp; <kbd>←↑↓→</kbd> Ecke / Muster verschieben<br>
    <kbd>Q</kbd> <kbd>E</kbd> Muster drehen (Shift = 15°)
  </div>
</div>
<input type="file" id="file" accept=".svg,image/svg+xml" multiple hidden>

<script>
'use strict';
/* ============ Zustand ============ */
const S={
  mode:'proj',
  ref:{w:600,h:450},
  handles:[[.25,.2],[.75,.2],[.75,.8],[.25,.8]],   // normalisiert (0..1) im Fenster
  active:0, gridStep:10, gridProj:false,
  lineW:1.5, fill:false, fillA:.15,
  patterns:[], sel:null, nextId:1
};
const $=id=>document.getElementById(id);
const cv=$('cv'), ctx=cv.getContext('2d');
let dpr=1, H=null, Hinv=null, dirty=true;

/* ============ Mathe: Homographie ============ */
function gauss(A,b){
  const n=b.length;
  for(let i=0;i<n;i++)A[i].push(b[i]);
  for(let c=0;c<n;c++){
    let p=c;
    for(let r=c+1;r<n;r++)if(Math.abs(A[r][c])>Math.abs(A[p][c]))p=r;
    [A[c],A[p]]=[A[p],A[c]];
    const d=A[c][c]; if(Math.abs(d)<1e-12)return null;
    for(let k=c;k<=n;k++)A[c][k]/=d;
    for(let r=0;r<n;r++){
      if(r===c)continue; const f=A[r][c]; if(!f)continue;
      for(let k=c;k<=n;k++)A[r][k]-=f*A[c][k];
    }
  }
  return A.map(r=>r[n]);
}
function solveH(src,dst){
  const A=[],b=[];
  for(let i=0;i<4;i++){
    const [x,y]=src[i],[u,v]=dst[i];
    A.push([x,y,1,0,0,0,-u*x,-u*y]); b.push(u);
    A.push([0,0,0,x,y,1,-v*x,-v*y]); b.push(v);
  }
  const h=gauss(A,b); return h?[...h,1]:null;
}
function inv3(m){
  const [a,b,c,d,e,f,g,h,i]=m;
  const A=e*i-f*h,B=-(d*i-f*g),C=d*h-e*g, det=a*A+b*B+c*C;
  if(!det)return null;
  return [A,-(b*i-c*h),(b*f-c*e),B,(a*i-c*g),-(a*f-c*d),C,-(a*h-b*g),(a*e-b*d)].map(x=>x/det);
}
function ap(m,x,y){
  const w=m[6]*x+m[7]*y+m[8];
  return [(m[0]*x+m[1]*y+m[2])/w,(m[3]*x+m[4]*y+m[5])/w];
}
function updateH(){
  const iw=innerWidth, ih=innerHeight;
  const dst=S.handles.map(h=>[h[0]*iw,h[1]*ih]);
  const src=[[0,0],[S.ref.w,0],[S.ref.w,S.ref.h],[0,S.ref.h]];
  const h=solveH(src,dst), i=h&&inv3(h);
  if(h&&i&&h.every(Number.isFinite)&&i.every(Number.isFinite)){H=h;Hinv=i;}
  if(H){
    const c=[S.ref.w/2,S.ref.h/2], p=ap(H,c[0],c[1]), px=ap(H,c[0]+10,c[1]), py=ap(H,c[0],c[1]+10);
    const sx=Math.hypot(px[0]-p[0],px[1]-p[1])/10, sy=Math.hypot(py[0]-p[0],py[1]-p[1])/10;
    $('scaleInfo').textContent=`Maßstab (Mitte): ${sx.toFixed(2)} px/mm in X · ${sy.toFixed(2)} px/mm in Y`;
  }
  dirty=true;
}
const toWorld=(x,y)=>Hinv?ap(Hinv,x,y):[0,0];

/* ============ SVG → Polylinien in mm ============ */
function arcToCubics(x1,y1,rx,ry,phiDeg,fa,fs,x2,y2){
  if(x1===x2&&y1===y2)return [];
  rx=Math.abs(rx);ry=Math.abs(ry);
  if(!rx||!ry)return [[x2,y2,x2,y2,x2,y2]];
  const phi=phiDeg*Math.PI/180,cp=Math.cos(phi),sp=Math.sin(phi);
  const dx=(x1-x2)/2,dy=(y1-y2)/2;
  const x1p=cp*dx+sp*dy,y1p=-sp*dx+cp*dy;
  const lam=x1p*x1p/(rx*rx)+y1p*y1p/(ry*ry);
  if(lam>1){const s=Math.sqrt(lam);rx*=s;ry*=s;}
  const sign=fa===fs?-1:1;
  const num=rx*rx*ry*ry-rx*rx*y1p*y1p-ry*ry*x1p*x1p, den=rx*rx*y1p*y1p+ry*ry*x1p*x1p;
  const co=sign*Math.sqrt(Math.max(0,num/den));
  const cxp=co*rx*y1p/ry, cyp=-co*ry*x1p/rx;
  const cx=cp*cxp-sp*cyp+(x1+x2)/2, cy=sp*cxp+cp*cyp+(y1+y2)/2;
  const ang=(ux,uy,vx,vy)=>Math.atan2(ux*vy-uy*vx,ux*vx+uy*vy);
  const th1=ang(1,0,(x1p-cxp)/rx,(y1p-cyp)/ry);
  let dth=ang((x1p-cxp)/rx,(y1p-cyp)/ry,(-x1p-cxp)/rx,(-y1p-cyp)/ry);
  if(!fs&&dth>0)dth-=2*Math.PI; if(fs&&dth<0)dth+=2*Math.PI;
  const n=Math.max(1,Math.ceil(Math.abs(dth)/(Math.PI/2)-1e-9)), dl=dth/n, t=4/3*Math.tan(dl/4);
  const M=(px,py)=>[cx+cp*rx*px-sp*ry*py, cy+sp*rx*px+cp*ry*py];
  const out=[]; let a=th1;
  for(let k=0;k<n;k++){
    const c1=Math.cos(a),s1=Math.sin(a),a2=a+dl,c2=Math.cos(a2),s2=Math.sin(a2);
    out.push([...M(c1-t*s1,s1+t*c1),...M(c2+t*s2,s2-t*c2),...M(c2,s2)]);
    a=a2;
  }
  return out;
}
function parsePath(d){
  const segs=[],n=d.length; let i=0,cmd='',cx=0,cy=0,sx=0,sy=0,lc=null,lq=null,needM=false;
  const NUM=/[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/y;
  const ws=()=>{while(i<n){const c=d.charCodeAt(i);if(c===32||c===44||c===9||c===10||c===13)i++;else break;}};
  const num=()=>{ws();NUM.lastIndex=i;const m=NUM.exec(d);if(!m)throw 0;i=NUM.lastIndex;return parseFloat(m[0]);};
  const flag=()=>{ws();return d[i++]==='1'?1:0;};
  const more=()=>{ws();return i<n&&/[-+.\d]/.test(d[i]);};
  const ensure=()=>{if(needM){segs.push(['M',cx,cy]);needM=false;}};
  try{
    while(true){
      ws(); if(i>=n)break;
      if(/[A-Za-z]/.test(d[i])){cmd=d[i++];}
      else if(!cmd||cmd==='Z'||cmd==='z'||!more())break;
      const rel=cmd===cmd.toLowerCase(),C=cmd.toUpperCase(),ox=rel?cx:0,oy=rel?cy:0;
      switch(C){
        case 'Z':segs.push(['Z']);cx=sx;cy=sy;needM=true;lc=lq=null;break;
        case 'M':{const x=num()+ox,y=num()+oy;segs.push(['M',x,y]);cx=sx=x;cy=sy=y;needM=false;cmd=rel?'l':'L';lc=lq=null;break;}
        case 'L':{ensure();const x=num()+ox,y=num()+oy;segs.push(['L',x,y]);cx=x;cy=y;lc=lq=null;break;}
        case 'H':{ensure();const x=num()+ox;segs.push(['L',x,cy]);cx=x;lc=lq=null;break;}
        case 'V':{ensure();const y=num()+oy;segs.push(['L',cx,y]);cy=y;lc=lq=null;break;}
        case 'C':{ensure();const a=num()+ox,b=num()+oy,c=num()+ox,e=num()+oy,x=num()+ox,y=num()+oy;
          segs.push(['C',a,b,c,e,x,y]);lc=[c,e];lq=null;cx=x;cy=y;break;}
        case 'S':{ensure();const a=lc?2*cx-lc[0]:cx,b=lc?2*cy-lc[1]:cy;
          const c=num()+ox,e=num()+oy,x=num()+ox,y=num()+oy;
          segs.push(['C',a,b,c,e,x,y]);lc=[c,e];lq=null;cx=x;cy=y;break;}
        case 'Q':{ensure();const qx=num()+ox,qy=num()+oy,x=num()+ox,y=num()+oy;
          segs.push(['C',cx+2/3*(qx-cx),cy+2/3*(qy-cy),x+2/3*(qx-x),y+2/3*(qy-y),x,y]);
          lq=[qx,qy];lc=null;cx=x;cy=y;break;}
        case 'T':{ensure();const qx=lq?2*cx-lq[0]:cx,qy=lq?2*cy-lq[1]:cy,x=num()+ox,y=num()+oy;
          segs.push(['C',cx+2/3*(qx-cx),cy+2/3*(qy-cy),x+2/3*(qx-x),y+2/3*(qy-y),x,y]);
          lq=[qx,qy];lc=null;cx=x;cy=y;break;}
        case 'A':{ensure();const rx=num(),ry=num(),rot=num(),fa=flag(),fs=flag(),x=num()+ox,y=num()+oy;
          for(const c of arcToCubics(cx,cy,rx,ry,rot,fa,fs,x,y))segs.push(['C',...c]);
          cx=x;cy=y;lc=lq=null;break;}
        default:i++;
      }
    }
  }catch(e){}
  return segs;
}
const NUMS=/[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g;
function shapeToD(el){
  const f=a=>parseFloat(el.getAttribute(a))||0, t=el.tagName.toLowerCase();
  if(t==='path')return el.getAttribute('d')||'';
  if(t==='line')return `M${f('x1')} ${f('y1')}L${f('x2')} ${f('y2')}`;
  if(t==='polyline'||t==='polygon'){
    const v=(el.getAttribute('points')||'').match(NUMS)||[]; if(v.length<4)return '';
    let d='M'+v[0]+' '+v[1]; for(let i=2;i+1<v.length;i+=2)d+='L'+v[i]+' '+v[i+1];
    return d+(t==='polygon'?'Z':'');
  }
  if(t==='circle'){const cx=f('cx'),cy=f('cy'),r=f('r');return `M${cx-r} ${cy}A${r} ${r} 0 1 0 ${cx+r} ${cy}A${r} ${r} 0 1 0 ${cx-r} ${cy}Z`;}
  if(t==='ellipse'){const cx=f('cx'),cy=f('cy'),rx=f('rx'),ry=f('ry');return `M${cx-rx} ${cy}A${rx} ${ry} 0 1 0 ${cx+rx} ${cy}A${rx} ${ry} 0 1 0 ${cx-rx} ${cy}Z`;}
  if(t==='rect'){
    const x=f('x'),y=f('y'),w=f('width'),h=f('height');
    let rx=el.hasAttribute('rx')?f('rx'):null, ry=el.hasAttribute('ry')?f('ry'):null;
    if(rx===null&&ry!==null)rx=ry; if(ry===null&&rx!==null)ry=rx;
    rx=Math.min(rx||0,w/2);ry=Math.min(ry||0,h/2);
    if(!rx||!ry)return `M${x} ${y}H${x+w}V${y+h}H${x}Z`;
    return `M${x+rx} ${y}H${x+w-rx}A${rx} ${ry} 0 0 1 ${x+w} ${y+ry}V${y+h-ry}A${rx} ${ry} 0 0 1 ${x+w-rx} ${y+h}H${x+rx}A${rx} ${ry} 0 0 1 ${x} ${y+h-ry}V${y+ry}A${rx} ${ry} 0 0 1 ${x+rx} ${y}Z`;
  }
  return '';
}
const dist=(a,b)=>Math.hypot(a[0]-b[0],a[1]-b[1]);
function toPolys(segs,M,k){
  const T=(x,y)=>[(M.a*x+M.c*y+M.e)*k,(M.b*x+M.d*y+M.f)*k];
  const out=[]; let cur=null;
  for(const s of segs){
    if(s[0]==='M'){cur={pts:[T(s[1],s[2])],closed:false};out.push(cur);}
    else if(!cur)continue;
    else if(s[0]==='L')cur.pts.push(T(s[1],s[2]));
    else if(s[0]==='Z')cur.closed=true;
    else if(s[0]==='C'){
      const p0=cur.pts[cur.pts.length-1],p1=T(s[1],s[2]),p2=T(s[3],s[4]),p3=T(s[5],s[6]);
      const len=dist(p0,p1)+dist(p1,p2)+dist(p2,p3);
      const n=Math.min(400,Math.max(4,Math.ceil(len/0.8)));
      for(let j=1;j<=n;j++){
        const t=j/n,u=1-t,a=u*u*u,b=3*u*u*t,c=3*u*t*t,d=t*t*t;
        cur.pts.push([a*p0[0]+b*p1[0]+c*p2[0]+d*p3[0],a*p0[1]+b*p1[1]+c*p2[1]+d*p3[1]]);
      }
    }
  }
  return out.filter(p=>p.pts.length>1);
}
function dashPoly(pts,closed,arr){
  const P=closed?[...pts,pts[0]]:pts, out=[];
  let ai=0,rem=arr[0],on=true,cur=[P[0]];
  for(let i=1;i<P.length;i++){
    const [x0,y0]=P[i-1],[x1,y1]=P[i],dx=x1-x0,dy=y1-y0,L=Math.hypot(dx,dy);
    let pos=0;
    while(L-pos>rem){
      pos+=rem; const x=x0+dx*pos/L,y=y0+dy*pos/L;
      if(on){cur.push([x,y]);out.push(cur);cur=null;}else cur=[[x,y]];
      on=!on; ai=(ai+1)%arr.length; rem=arr[ai];
    }
    rem-=(L-pos);
    if(on&&cur)cur.push([x1,y1]);
  }
  if(on&&cur&&cur.length>1)out.push(cur);
  return out;
}
const UF={mm:1,cm:10,in:25.4,pt:25.4/72,pc:25.4/6,px:25.4/96};
function mmPerUnit(svg,mode){
  if(mode==='mm')return 1; if(mode==='cm')return 10; if(mode==='in')return 25.4;
  if(mode==='px')return UF.px; if(mode==='pt')return UF.pt;
  const vb=svg.viewBox&&svg.viewBox.baseVal;
  const m=/^\s*([-+]?[\d.]+(?:e[-+]?\d+)?)\s*(mm|cm|in|pt|pc|px)?\s*$/i.exec(svg.getAttribute('width')||'');
  if(vb&&vb.width>0&&m)return parseFloat(m[1])*UF[(m[2]||'px').toLowerCase()]/vb.width;
  return UF.px;
}
function hex(c){
  const m=/rgba?\(\s*(\d+)[ ,]+(\d+)[ ,]+(\d+)/.exec(c); if(!m)return null;
  return '#'+[m[1],m[2],m[3]].map(v=>(+v).toString(16).padStart(2,'0')).join('');
}
function flattenSvg(text,unit){
  const doc=new DOMParser().parseFromString(text,'image/svg+xml');
  const root=doc.documentElement;
  if(!root||root.nodeName.toLowerCase()!=='svg'||doc.querySelector('parsererror'))throw new Error('Keine gültige SVG-Datei.');
  root.querySelectorAll('script,foreignObject').forEach(n=>n.remove());
  root.querySelectorAll('*').forEach(n=>[...n.attributes].forEach(a=>{if(/^on/i.test(a.name))n.removeAttribute(a.name);}));
  const host=$('svghost'); host.replaceChildren();
  const svg=document.importNode(root,true); host.appendChild(svg);
  const k=mmPerUnit(svg,unit), paths=[], keys={};
  try{
    const sm=svg.getScreenCTM(); if(!sm)throw new Error('SVG konnte nicht ausgewertet werden.');
    const smi=sm.inverse();
    svg.querySelectorAll('path,rect,circle,ellipse,line,polyline,polygon').forEach(el=>{
      if(el.closest('defs,clipPath,mask,symbol,marker,pattern'))return;
      const cs=getComputedStyle(el); if(cs.display==='none')return;
      let col=cs.stroke; if(!col||col==='none'){col=cs.fill; if(!col||col==='none')return;}
      const key=hex(col); if(!key)return;
      const em=el.getScreenCTM(); if(!em)return;
      const M=smi.multiply(em);
      const polys=toPolys(parsePath(shapeToD(el)),M,k); if(!polys.length)return;
      let dash=null;
      const da=cs.strokeDasharray;
      if(da&&da!=='none'&&cs.stroke!=='none'){
        const sc=Math.sqrt(Math.abs(M.a*M.d-M.b*M.c))*k;
        let arr=(da.match(NUMS)||[]).map(v=>parseFloat(v)*sc).filter(v=>v>0);
        if(arr.length&&arr.length%2)arr=arr.concat(arr);
        if(arr.length&&arr.reduce((a,b)=>a+b,0)>0.3)dash=arr;
      }
      for(const p of polys){
        if(dash){
          let L=0;for(let i=1;i<p.pts.length;i++)L+=dist(p.pts[i-1],p.pts[i]);
          if(L/dash.reduce((a,b)=>a+b,0)<20000){
            for(const q of dashPoly(p.pts,p.closed,dash))paths.push({key,pts:q,closed:false});
            continue;
          }
        }
        paths.push({key,pts:p.pts,closed:p.closed});
      }
      keys[key]=(keys[key]||0)+1;
    });
  }finally{host.replaceChildren();}
  if(!paths.length)throw new Error('Keine Linien oder Formen in der SVG gefunden.');
  let x0=1e18,y0=1e18,x1=-1e18,y1=-1e18;
  for(const p of paths)for(const q of p.pts){x0=Math.min(x0,q[0]);y0=Math.min(y0,q[1]);x1=Math.max(x1,q[0]);y1=Math.max(y1,q[1]);}
  for(const p of paths)for(const q of p.pts){q[0]-=x0;q[1]-=y0;}
  return {paths,keys,w:x1-x0,h:y1-y0};
}

/* ============ Muster ============ */
function defaultColor(key){
  const r=parseInt(key.slice(1,3),16),g=parseInt(key.slice(3,5),16),b=parseInt(key.slice(5,7),16);
  return Math.max(r,g,b)<90?'#ffffff':key;
}
function rebuild(pt){
  const r=flattenSvg(pt.text,pt.unit);
  pt.paths=r.paths;pt.w=r.w;pt.h=r.h;
  for(const key in r.keys){
    if(!pt.groups[key])pt.groups[key]={visible:true,color:defaultColor(key)};
    pt.groups[key].count=r.keys[key];
  }
  for(const key in pt.groups)if(!r.keys[key])delete pt.groups[key];
}
function addPattern(name,text){
  try{
    const pt={id:S.nextId++,name,text,unit:'auto',x:S.ref.w/2,y:S.ref.h/2,rot:0,scale:1,mirror:false,groups:{}};
    rebuild(pt); S.patterns.push(pt); S.sel=pt.id;
    msg(`„${name}“ geladen: ${pt.w.toFixed(1)} × ${pt.h.toFixed(1)} mm`);
    renderAll(); dirty=true;
  }catch(e){msg(`${name}: ${e.message||'Fehler beim Laden'}`);}
}
const selPat=()=>S.patterns.find(p=>p.id===S.sel)||null;
function pToWorld(p,pt){
  let x=p[0]-pt.w/2,y=p[1]-pt.h/2; if(pt.mirror)x=-x; x*=pt.scale;y*=pt.scale;
  const a=pt.rot*Math.PI/180,c=Math.cos(a),s=Math.sin(a);
  return [pt.x+x*c-y*s,pt.y+x*s+y*c];
}
function worldToP(wx,wy,pt){
  let x=wx-pt.x,y=wy-pt.y; const a=-pt.rot*Math.PI/180,c=Math.cos(a),s=Math.sin(a);
  [x,y]=[x*c-y*s,x*s+y*c]; x/=pt.scale;y/=pt.scale; if(pt.mirror)x=-x;
  return [x+pt.w/2,y+pt.h/2];
}
function pick(w){
  const inside=pt=>{const p=worldToP(w[0],w[1],pt);return p[0]>=0&&p[1]>=0&&p[0]<=pt.w&&p[1]<=pt.h;};
  const s=selPat(); if(s&&inside(s))return s;
  for(let i=S.patterns.length-1;i>=0;i--)if(inside(S.patterns[i]))return S.patterns[i];
  return null;
}

const DEMO=`<svg xmlns="http://www.w3.org/2000/svg" width="300mm" height="400mm" viewBox="0 0 300 400">
<path d="M20 380 L20 140 C20 70 80 25 150 25 C220 25 280 70 280 140 L280 380 Z" fill="none" stroke="#000" stroke-width="1"/>
<path d="M150 70 L150 340" fill="none" stroke="#e03030" stroke-width="1" stroke-dasharray="10 5"/>
<path d="M150 70 l-7 16 M150 70 l7 16 M150 340 l-7 -16 M150 340 l7 -16" fill="none" stroke="#e03030"/>
<rect x="100" y="150" width="100" height="100" fill="none" stroke="#000"/>
<circle cx="150" cy="200" r="30" fill="none" stroke="#000"/>
<path d="M20 260 l12 0 M280 260 l-12 0 M20 320 l12 0 M280 320 l-12 0" fill="none" stroke="#000"/>
<path d="M60 360 A25 25 0 0 1 110 360" fill="none" stroke="#000"/>
</svg>`;

/* ============ Zeichnen ============ */
function draw(){
  dirty=false;
  const iw=innerWidth,ih=innerHeight;
  ctx.setTransform(dpr,0,0,dpr,0,0);
  ctx.fillStyle='#000';ctx.fillRect(0,0,iw,ih);
  if(!H)return;
  const cal=S.mode==='cal';
  if(cal||S.gridProj)drawGrid(iw,ih);
  if(cal)drawRef();
  drawPatterns();
  if(cal)drawHandles(iw,ih);
}
function drawGrid(iw,ih){
  const cs=[[0,0],[iw,0],[iw,ih],[0,ih]].map(p=>toWorld(p[0],p[1]));
  const cl=v=>Math.max(-6000,Math.min(6000,v));
  const minX=cl(Math.min(...cs.map(c=>c[0]))),maxX=cl(Math.max(...cs.map(c=>c[0])));
  const minY=cl(Math.min(...cs.map(c=>c[1]))),maxY=cl(Math.max(...cs.map(c=>c[1])));
  const st=S.gridStep, alpha=[.2,.42,.85], lw=[1,1,1.5];
  const level=v=>(v%100===0)?2:((v%50===0&&st<=50)?1:0);
  for(let lv=0;lv<3;lv++){
    ctx.beginPath();
    let cnt=0;
    for(let i=Math.ceil(minX/st);i*st<=maxX&&cnt<800;i++,cnt++){
      const v=Math.round(i*st); if(level(v)!==lv)continue;
      const a=ap(H,v,minY),b=ap(H,v,maxY); ctx.moveTo(a[0],a[1]);ctx.lineTo(b[0],b[1]);
    }
    cnt=0;
    for(let j=Math.ceil(minY/st);j*st<=maxY&&cnt<800;j++,cnt++){
      const v=Math.round(j*st); if(level(v)!==lv)continue;
      const a=ap(H,minX,v),b=ap(H,maxX,v); ctx.moveTo(a[0],a[1]);ctx.lineTo(b[0],b[1]);
    }
    ctx.strokeStyle=`rgba(255,255,255,${alpha[lv]})`;ctx.lineWidth=lw[lv];ctx.stroke();
  }
}
function drawRef(){
  const {w,h}=S.ref,P=[[0,0],[w,0],[w,h],[0,h]].map(p=>ap(H,p[0],p[1]));
  ctx.beginPath();P.forEach((p,i)=>i?ctx.lineTo(p[0],p[1]):ctx.moveTo(p[0],p[1]));ctx.closePath();
  ctx.strokeStyle='#ff9f0a';ctx.lineWidth=1;ctx.stroke();
}
function drawHandles(iw,ih){
  const lab=[[0,0],[S.ref.w,0],[S.ref.w,S.ref.h],[0,S.ref.h]];
  ctx.font='11px system-ui,sans-serif';ctx.textBaseline='middle';
  S.handles.forEach((h,i)=>{
    const x=h[0]*iw,y=h[1]*ih,act=i===S.active;
    ctx.strokeStyle=act?'#fff':'#ff9f0a';ctx.lineWidth=1;
    ctx.beginPath();
    ctx.moveTo(x-34,y);ctx.lineTo(x-4,y);ctx.moveTo(x+4,y);ctx.lineTo(x+34,y);
    ctx.moveTo(x,y-34);ctx.lineTo(x,y-4);ctx.moveTo(x,y+4);ctx.lineTo(x,y+34);ctx.stroke();
    ctx.beginPath();ctx.arc(x,y,11,0,Math.PI*2);ctx.stroke();
    ctx.fillStyle=act?'#fff':'#ff9f0a';
    const right=x<iw/2?1:-1; ctx.textAlign=right>0?'left':'right';
    ctx.fillText(`${i+1}  (${lab[i][0]} / ${lab[i][1]} mm)`,x+right*16,y+(y<ih/2?-20:20));
  });
}
function drawPatterns(){
  ctx.lineJoin='round';ctx.lineCap='round';
  for(const pt of S.patterns){
    for(const p of pt.paths){
      const g=pt.groups[p.key]; if(!g||!g.visible)continue;
      ctx.beginPath();
      for(let i=0;i<p.pts.length;i++){
        const w=pToWorld(p.pts[i],pt),s=ap(H,w[0],w[1]);
        i?ctx.lineTo(s[0],s[1]):ctx.moveTo(s[0],s[1]);
      }
      if(p.closed)ctx.closePath();
      if(S.fill&&p.closed){ctx.globalAlpha=S.fillA;ctx.fillStyle=g.color;ctx.fill();ctx.globalAlpha=1;}
      ctx.strokeStyle=g.color;ctx.lineWidth=S.lineW;ctx.stroke();
    }
  }
}
(function loop(){if(dirty)draw();requestAnimationFrame(loop);})();

/* ============ UI ============ */
let msgT=null;
function msg(t){const m=$('msg');m.textContent=t;clearTimeout(msgT);msgT=setTimeout(()=>m.textContent='',7000);}
function setMode(m){
  S.mode=m;
  $('mProj').classList.toggle('on',m==='proj');$('mCal').classList.toggle('on',m==='cal');
  $('secCal').style.display=m==='cal'?'':'none';
  cv.style.cursor=m==='cal'?'crosshair':'default';
  dirty=true;
}
function renderAll(){renderList();renderProps();}
function renderList(){
  const box=$('list');box.replaceChildren();
  for(const pt of S.patterns){
    const row=document.createElement('div');row.className='item';
    const b=document.createElement('button');b.className='name'+(pt.id===S.sel?' on':'');
    b.textContent=`${pt.name}  ·  ${pt.w.toFixed(0)}×${pt.h.toFixed(0)}`;
    b.onclick=()=>{S.sel=pt.id;renderAll();};
    const d=document.createElement('button');d.textContent='✕';d.title='Entfernen';
    d.onclick=()=>{S.patterns=S.patterns.filter(p=>p!==pt);if(S.sel===pt.id)S.sel=S.patterns.length?S.patterns[S.patterns.length-1].id:null;renderAll();dirty=true;};
    row.append(b,d);box.append(row);
  }
}
function syncFields(){
  const pt=selPat();if(!pt)return;
  $('pX').value=+pt.x.toFixed(1);$('pY').value=+pt.y.toFixed(1);
  $('pRot').value=+pt.rot.toFixed(1);$('pScale').value=+(pt.scale*100).toFixed(2);
  $('pMirror').checked=pt.mirror;$('pUnit').value=pt.unit;
  $('pInfo').textContent=`Größe: ${(pt.w*pt.scale).toFixed(1)} × ${(pt.h*pt.scale).toFixed(1)} mm`;
}
function renderProps(){
  const pt=selPat();$('props').style.display=pt?'':'none';
  if(!pt)return;
  syncFields();
  const box=$('groups');box.replaceChildren();
  for(const key in pt.groups){
    const g=pt.groups[key],row=document.createElement('div');row.className='grp';
    const sw=document.createElement('span');sw.className='sw';sw.style.background=key;sw.title='Originalfarbe in der SVG';
    const cb=document.createElement('input');cb.type='checkbox';cb.checked=g.visible;
    cb.onchange=()=>{g.visible=cb.checked;dirty=true;};
    const n=document.createElement('span');n.className='n';n.textContent=`${key} · ${g.count}`;
    const col=document.createElement('input');col.type='color';col.value=g.color;col.title='Anzeigefarbe';
    col.oninput=()=>{g.color=col.value;dirty=true;};
    row.append(sw,cb,n,col);box.append(row);
  }
}
function save(){
  try{localStorage.setItem('spp.v1',JSON.stringify({handles:S.handles,ref:S.ref,gridStep:S.gridStep,lineW:S.lineW,fill:S.fill,fillA:S.fillA,gridProj:S.gridProj}));}catch(e){}
}
function load(){
  try{
    const d=JSON.parse(localStorage.getItem('spp.v1')||'null');if(!d)return;
    if(Array.isArray(d.handles)&&d.handles.length===4)S.handles=d.handles;
    if(d.ref)S.ref=d.ref;
    ['gridStep','lineW','fill','fillA','gridProj'].forEach(k=>{if(d[k]!==undefined)S[k]=d[k];});
  }catch(e){}
}
function resetCorners(){
  const iw=innerWidth,ih=innerHeight,k=Math.min(.7*iw/S.ref.w,.7*ih/S.ref.h),w=S.ref.w*k,h=S.ref.h*k;
  const x0=(iw-w)/2/iw,x1=(iw+w)/2/iw,y0=(ih-h)/2/ih,y1=(ih+h)/2/ih;
  S.handles=[[x0,y0],[x1,y0],[x1,y1],[x0,y1]];
}
function syncStatic(){
  $('refW').value=S.ref.w;$('refH').value=S.ref.h;$('gridStep').value=S.gridStep;
  $('lineW').value=S.lineW;$('fill').checked=S.fill;$('fillA').value=S.fillA;$('gridProj').checked=S.gridProj;
  document.querySelectorAll('#corner button').forEach(b=>b.classList.toggle('on',+b.dataset.i===S.active));
}
const changed=()=>{updateH();save();};

/* --- Panel-Events --- */
$('mProj').onclick=()=>setMode('proj');$('mCal').onclick=()=>setMode('cal');
$('btnFull').onclick=()=>{document.fullscreenElement?document.exitFullscreen():document.documentElement.requestFullscreen().catch(()=>{});};
$('btnHide').onclick=()=>{$('panel').classList.add('hidden');$('panel').classList.remove('peek');};
$('refW').oninput=e=>{const v=parseFloat(e.target.value);if(v>=10){S.ref.w=v;changed();}};
$('refH').oninput=e=>{const v=parseFloat(e.target.value);if(v>=10){S.ref.h=v;changed();}};
$('gridStep').onchange=e=>{S.gridStep=+e.target.value;dirty=true;save();};
$('resetCorners').onclick=()=>{resetCorners();changed();};
document.querySelectorAll('#corner button').forEach(b=>b.onclick=()=>{S.active=+b.dataset.i;syncStatic();dirty=true;});
$('lineW').oninput=e=>{S.lineW=+e.target.value;dirty=true;save();};
$('fill').onchange=e=>{S.fill=e.target.checked;dirty=true;save();};
$('fillA').oninput=e=>{S.fillA=+e.target.value;dirty=true;save();};
$('gridProj').onchange=e=>{S.gridProj=e.target.checked;dirty=true;save();};
$('btnLoad').onclick=()=>$('file').click();
$('file').onchange=e=>{addFiles(e.target.files);e.target.value='';};
$('btnDemo').onclick=()=>addPattern('Testmuster',DEMO);
async function addFiles(files){
  for(const f of files){
    if(!/\.svg$/i.test(f.name)&&f.type!=='image/svg+xml'){msg(`${f.name}: keine SVG-Datei`);continue;}
    addPattern(f.name.replace(/\.svg$/i,''),await f.text());
  }
}
const num=(id,fn)=>$(id).addEventListener('input',e=>{const pt=selPat(),v=parseFloat(e.target.value);if(pt&&Number.isFinite(v)){fn(pt,v);$('pInfo').textContent=`Größe: ${(pt.w*pt.scale).toFixed(1)} × ${(pt.h*pt.scale).toFixed(1)} mm`;dirty=true;}});
num('pX',(p,v)=>p.x=v);num('pY',(p,v)=>p.y=v);num('pRot',(p,v)=>p.rot=v);num('pScale',(p,v)=>{if(v>0)p.scale=v/100;});
$('pMirror').onchange=e=>{const p=selPat();if(p){p.mirror=e.target.checked;dirty=true;}};
$('pUnit').onchange=e=>{const p=selPat();if(!p)return;p.unit=e.target.value;try{rebuild(p);renderAll();dirty=true;}catch(err){msg(err.message);}};
$('pRotM').onclick=()=>{const p=selPat();if(p){p.rot-=90;syncFields();dirty=true;}};
$('pRotP').onclick=()=>{const p=selPat();if(p){p.rot+=90;syncFields();dirty=true;}};
$('pCenter').onclick=()=>{const p=selPat();if(p){p.x=S.ref.w/2;p.y=S.ref.h/2;syncFields();dirty=true;}};

/* --- Maus auf der Fläche --- */
let drag=null;
cv.addEventListener('pointerdown',e=>{
  const x=e.clientX,y=e.clientY,iw=innerWidth,ih=innerHeight;
  if(S.mode==='cal'){
    let best=-1,bd=30;
    S.handles.forEach((h,i)=>{const d=Math.hypot(h[0]*iw-x,h[1]*ih-y);if(d<bd){bd=d;best=i;}});
    if(best>=0){S.active=best;drag={t:'h',i:best};cv.setPointerCapture(e.pointerId);syncStatic();dirty=true;}
  }else{
    const w=toWorld(x,y),pt=pick(w);
    if(pt){S.sel=pt.id;renderAll();drag={t:'p',pt,last:w};cv.setPointerCapture(e.pointerId);}
  }
});
cv.addEventListener('pointermove',e=>{
  if(!drag)return;
  if(drag.t==='h'){
    S.handles[drag.i]=[Math.max(0,Math.min(1,e.clientX/innerWidth)),Math.max(0,Math.min(1,e.clientY/innerHeight))];
    updateH();
  }else{
    const w=toWorld(e.clientX,e.clientY);
    drag.pt.x+=w[0]-drag.last[0];drag.pt.y+=w[1]-drag.last[1];drag.last=w;
    syncFields();dirty=true;
  }
});
const endDrag=()=>{if(drag&&drag.t==='h')save();drag=null;};
cv.addEventListener('pointerup',endDrag);cv.addEventListener('pointercancel',endDrag);

/* --- Panel am rechten Rand kurz einblenden --- */
addEventListener('mousemove',e=>{
  const p=$('panel');if(!p.classList.contains('hidden'))return;
  if(e.clientX>innerWidth-6)p.classList.add('peek');
  else if(e.clientX<innerWidth-320)p.classList.remove('peek');
});

/* --- Drag & Drop --- */
addEventListener('dragover',e=>e.preventDefault());
addEventListener('drop',e=>{e.preventDefault();if(e.dataTransfer&&e.dataTransfer.files.length)addFiles(e.dataTransfer.files);});

/* --- Tastatur --- */
addEventListener('keydown',e=>{
  if(e.target.matches&&e.target.matches('input[type=number],input[type=range],select,textarea'))return;
  if(e.ctrlKey||e.metaKey||e.altKey)return;
  const k=e.key.toLowerCase(),big=e.shiftKey;
  if(k==='h'){const p=$('panel');p.classList.toggle('hidden');p.classList.remove('peek');}
  else if(k==='f')$('btnFull').click();
  else if(k==='c')setMode(S.mode==='cal'?'proj':'cal');
  else if(k==='g'){S.gridProj=!S.gridProj;syncStatic();dirty=true;save();}
  else if(S.mode==='cal'&&'1234'.includes(k)&&k.length===1){S.active=+k-1;syncStatic();dirty=true;}
  else if(k.startsWith('arrow')){
    const dx=k==='arrowleft'?-1:k==='arrowright'?1:0,dy=k==='arrowup'?-1:k==='arrowdown'?1:0;
    if(S.mode==='cal'){
      const h=S.handles[S.active],st=big?10:1;
      h[0]=Math.max(0,Math.min(1,h[0]+dx*st/innerWidth));h[1]=Math.max(0,Math.min(1,h[1]+dy*st/innerHeight));
      changed();
    }else{
      const pt=selPat();if(pt){const st=big?10:1;pt.x+=dx*st;pt.y+=dy*st;syncFields();dirty=true;}
    }
    e.preventDefault();
  }
  else if((k==='q'||k==='e')&&S.mode==='proj'){
    const pt=selPat();if(pt){pt.rot+=(k==='e'?1:-1)*(big?15:1);syncFields();dirty=true;}
  }
});

addEventListener('resize',()=>{resize();});
function resize(){dpr=window.devicePixelRatio||1;cv.width=Math.round(innerWidth*dpr);cv.height=Math.round(innerHeight*dpr);updateH();}

/* ============ Start ============ */
load();
if(!localStorage.getItem('spp.v1'))resetCorners();
syncStatic();setMode('cal');resize();
</script>
</body>
</html>