Files
2026-11-24 23:51:26 +00:00

51 lines
2.1 KiB
JavaScript

// Canvas2D backend: rasterises a render list (draw-ops in screen coordinates).
import { colorCss } from '../src/scene.mjs';
function roundRectPath(ctx, r, radius) {
ctx.beginPath();
const rad = Math.min(radius, r.w / 2, r.h / 2);
if (rad > 0) ctx.roundRect(r.x, r.y, r.w, r.h, rad); else ctx.rect(r.x, r.y, r.w, r.h);
}
export function paint(ctx, ops, screen) {
ctx.clearRect(0, 0, screen.w, screen.h);
let depth = 0;
for (const op of ops) {
const v = op.val;
switch (op.tag) {
case 'push-clip':
ctx.save(); depth++;
ctx.beginPath(); ctx.rect(v.x, v.y, v.w, v.h); ctx.clip();
break;
case 'pop-clip':
if (depth === 0) throw new Error('pop-clip without push-clip');
ctx.restore(); depth--;
break;
case 'fill-rect':
ctx.fillStyle = colorCss(v.color); roundRectPath(ctx, v.rect, v.radius); ctx.fill();
break;
case 'stroke-rect':
ctx.strokeStyle = colorCss(v.color); ctx.lineWidth = v.width;
roundRectPath(ctx, { x: v.rect.x + 0.5, y: v.rect.y + 0.5, w: v.rect.w - 1, h: v.rect.h - 1 }, v.radius); ctx.stroke();
break;
case 'line':
ctx.strokeStyle = colorCss(v.color); ctx.lineWidth = v.width;
ctx.beginPath(); ctx.moveTo(v.start.x + 0.5, v.start.y + 0.5); ctx.lineTo(v.end.x + 0.5, v.end.y + 0.5); ctx.stroke();
break;
case 'circle':
ctx.beginPath(); ctx.arc(v.center.x, v.center.y, v.radius, 0, Math.PI * 2);
if (v.filled) { ctx.fillStyle = colorCss(v.color); ctx.fill(); }
else { ctx.strokeStyle = colorCss(v.color); ctx.lineWidth = 1.5; ctx.stroke(); }
break;
case 'text':
ctx.font = `${v.style.bold ? '600 ' : ''}${v.style.size}px system-ui, "DejaVu Sans", sans-serif`;
ctx.fillStyle = colorCss(v.style.color);
ctx.textAlign = v.style.align; ctx.textBaseline = 'middle';
ctx.fillText(v.text, v.origin.x, v.origin.y);
break;
default: throw new Error(`unknown draw-op ${op.tag}`);
}
}
if (depth !== 0) throw new Error(`unbalanced clip stack (${depth})`);
}