Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

feat(image): add Phase 5 text and vector tools

Augustus Otu49ff54e28808
diff --git a/apps/image/src/tools/text/text-engine.ts b/apps/image/src/tools/text/text-engine.ts
new file mode 100644
index 00000000..f71b2237
--- /dev/null
+++ b/apps/image/src/tools/text/text-engine.ts
@@ -0,0 +1,478 @@
+export type TextAlignment = 'left' | 'center' | 'right' | 'justify';
+export type TextBaseline = 'top' | 'middle' | 'bottom' | 'alphabetic';
+export type TextDirection = 'ltr' | 'rtl';
+export type TextDecoration = 'none' | 'underline' | 'strikethrough' | 'both';
+export type TextCase = 'none' | 'uppercase' | 'lowercase' | 'capitalize';
+
+export interface TextStyle {
+ fontFamily: string;
+ fontSize: number;
+ fontWeight: number;
+ fontStyle: 'normal' | 'italic' | 'oblique';
+ color: string;
+ opacity: number;
+ letterSpacing: number;
+ lineHeight: number;
+ textAlign: TextAlignment;
+ textBaseline: TextBaseline;
+ textDecoration: TextDecoration;
+ textCase: TextCase;
+ textDirection: TextDirection;
+ strokeColor: string;
+ strokeWidth: number;
+ shadowColor: string;
+ shadowBlur: number;
+ shadowOffsetX: number;
+ shadowOffsetY: number;
+ backgroundColor: string;
+ backgroundPadding: number;
+}
+
+export interface TextRun {
+ text: string;
+ style: Partial<TextStyle>;
+ startIndex: number;
+ endIndex: number;
+}
+
+export interface TextParagraph {
+ text: string;
+ runs: TextRun[];
+ alignment: TextAlignment;
+ indent: number;
+ spaceBefore: number;
+ spaceAfter: number;
+}
+
+export interface TextDocument {
+ paragraphs: TextParagraph[];
+ defaultStyle: TextStyle;
+ boundingBox: { width: number; height: number } | null;
+ wrapMode: 'none' | 'word' | 'character';
+}
+
+export interface TextMetrics {
+ width: number;
+ height: number;
+ lines: LineMetrics[];
+ actualBoundingBox: { left: number; right: number; top: number; bottom: number };
+}
+
+export interface LineMetrics {
+ text: string;
+ width: number;
+ height: number;
+ baseline: number;
+ runs: Array<{ text: string; style: TextStyle; x: number; width: number }>;
+}
+
+export const DEFAULT_TEXT_STYLE: TextStyle = {
+ fontFamily: 'Inter, system-ui, sans-serif',
+ fontSize: 24,
+ fontWeight: 400,
+ fontStyle: 'normal',
+ color: '#000000',
+ opacity: 1,
+ letterSpacing: 0,
+ lineHeight: 1.4,
+ textAlign: 'left',
+ textBaseline: 'alphabetic',
+ textDecoration: 'none',
+ textCase: 'none',
+ textDirection: 'ltr',
+ strokeColor: 'transparent',
+ strokeWidth: 0,
+ shadowColor: 'transparent',
+ shadowBlur: 0,
+ shadowOffsetX: 0,
+ shadowOffsetY: 0,
+ backgroundColor: 'transparent',
+ backgroundPadding: 0,
+};
+
+export const FONT_WEIGHTS: Record<string, number> = {
+ thin: 100,
+ extraLight: 200,
+ light: 300,
+ regular: 400,
+ medium: 500,
+ semiBold: 600,
+ bold: 700,
+ extraBold: 800,
+ black: 900,
+};
+
+function applyTextCase(text: string, textCase: TextCase): string {
+ switch (textCase) {
+ case 'uppercase':
+ return text.toUpperCase();
+ case 'lowercase':
+ return text.toLowerCase();
+ case 'capitalize':
+ return text.replace(/\b\w/g, (char) => char.toUpperCase());
+ default:
+ return text;
+ }
+}
+
+function buildFontString(style: TextStyle): string {
+ const fontStyle = style.fontStyle !== 'normal' ? style.fontStyle : '';
+ const fontWeight = style.fontWeight !== 400 ? style.fontWeight.toString() : '';
+ const fontSize = `${style.fontSize}px`;
+ const fontFamily = style.fontFamily;
+
+ return [fontStyle, fontWeight, fontSize, fontFamily].filter(Boolean).join(' ');
+}
+
+function mergeStyles(base: TextStyle, override: Partial<TextStyle>): TextStyle {
+ return { ...base, ...override };
+}
+
+export function measureText(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ text: string,
+ style: TextStyle
+): { width: number; height: number; ascent: number; descent: number } {
+ ctx.font = buildFontString(style);
+ ctx.textBaseline = style.textBaseline;
+
+ const metrics = ctx.measureText(applyTextCase(text, style.textCase));
+ const width = metrics.width + text.length * style.letterSpacing;
+ const height = style.fontSize * style.lineHeight;
+ const ascent = metrics.actualBoundingBoxAscent || style.fontSize * 0.8;
+ const descent = metrics.actualBoundingBoxDescent || style.fontSize * 0.2;
+
+ return { width, height, ascent, descent };
+}
+
+function wrapText(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ text: string,
+ style: TextStyle,
+ maxWidth: number,
+ wrapMode: 'none' | 'word' | 'character'
+): string[] {
+ if (wrapMode === 'none' || maxWidth <= 0) {
+ return [text];
+ }
+
+ const lines: string[] = [];
+ ctx.font = buildFontString(style);
+
+ if (wrapMode === 'character') {
+ let currentLine = '';
+ for (const char of text) {
+ const testLine = currentLine + char;
+ const metrics = ctx.measureText(testLine);
+ if (metrics.width > maxWidth && currentLine.length > 0) {
+ lines.push(currentLine);
+ currentLine = char;
+ } else {
+ currentLine = testLine;
+ }
+ }
+ if (currentLine) lines.push(currentLine);
+ return lines;
+ }
+
+ const words = text.split(/(\s+)/);
+ let currentLine = '';
+
+ for (const word of words) {
+ const testLine = currentLine + word;
+ const metrics = ctx.measureText(testLine);
+
+ if (metrics.width > maxWidth && currentLine.trim().length > 0) {
+ lines.push(currentLine.trim());
+ currentLine = word.trimStart();
+ } else {
+ currentLine = testLine;
+ }
+ }
+
+ if (currentLine.trim()) {
+ lines.push(currentLine.trim());
+ }
+
+ return lines.length > 0 ? lines : [''];
+}
+
+export function layoutText(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ document: TextDocument
+): TextMetrics {
+ const lines: LineMetrics[] = [];
+ let maxWidth = 0;
+ let totalHeight = 0;
+ const boundingWidth = document.boundingBox?.width || Infinity;
+
+ for (const paragraph of document.paragraphs) {
+ totalHeight += paragraph.spaceBefore;
+ const paragraphStyle = mergeStyles(document.defaultStyle, {});
+
+ const wrappedLines = wrapText(ctx, paragraph.text, paragraphStyle, boundingWidth, document.wrapMode);
+
+ for (const lineText of wrappedLines) {
+ const lineRuns: Array<{ text: string; style: TextStyle; x: number; width: number }> = [];
+ let lineWidth = paragraph.indent;
+ let lineHeight = 0;
+ let lineBaseline = 0;
+
+ let charIndex = 0;
+ const paragraphOffset = document.paragraphs.slice(0, document.paragraphs.indexOf(paragraph))
+ .reduce((acc, p) => acc + p.text.length + 1, 0);
+
+ for (let i = 0; i < lineText.length; ) {
+ const globalIndex = paragraphOffset + charIndex;
+ const applicableRun = paragraph.runs.find(
+ (run) => globalIndex >= run.startIndex && globalIndex < run.endIndex
+ );
+ const runStyle = mergeStyles(
+ document.defaultStyle,
+ applicableRun?.style || {}
+ );
+
+ let runEnd = lineText.length;
+ if (applicableRun) {
+ const runLocalEnd = applicableRun.endIndex - paragraphOffset;
+ runEnd = Math.min(runEnd, runLocalEnd - (charIndex - i));
+ }
+
+ const runText = lineText.slice(i, runEnd);
+ const measurement = measureText(ctx, runText, runStyle);
+
+ lineRuns.push({
+ text: runText,
+ style: runStyle,
+ x: lineWidth,
+ width: measurement.width,
+ });
+
+ lineWidth += measurement.width;
+ lineHeight = Math.max(lineHeight, measurement.height);
+ lineBaseline = Math.max(lineBaseline, measurement.ascent);
+
+ charIndex += runText.length;
+ i = runEnd;
+ }
+
+ let offsetX = 0;
+ if (paragraph.alignment === 'center') {
+ offsetX = (boundingWidth - lineWidth) / 2;
+ } else if (paragraph.alignment === 'right') {
+ offsetX = boundingWidth - lineWidth;
+ }
+
+ for (const run of lineRuns) {
+ run.x += offsetX;
+ }
+
+ lines.push({
+ text: lineText,
+ width: lineWidth,
+ height: lineHeight,
+ baseline: lineBaseline,
+ runs: lineRuns,
+ });
+
+ maxWidth = Math.max(maxWidth, lineWidth);
+ totalHeight += lineHeight;
+ }
+
+ totalHeight += paragraph.spaceAfter;
+ }
+
+ return {
+ width: maxWidth,
+ height: totalHeight,
+ lines,
+ actualBoundingBox: {
+ left: 0,
+ right: maxWidth,
+ top: 0,
+ bottom: totalHeight,
+ },
+ };
+}
+
+export function renderText(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ document: TextDocument,
+ x: number,
+ y: number
+): void {
+ const layout = layoutText(ctx, document);
+ let currentY = y;
+
+ ctx.save();
+
+ for (const line of layout.lines) {
+ for (const run of line.runs) {
+ const style = run.style;
+ const displayText = applyTextCase(run.text, style.textCase);
+ const drawX = x + run.x;
+ const drawY = currentY + line.baseline;
+
+ ctx.font = buildFontString(style);
+ ctx.textBaseline = 'alphabetic';
+ ctx.globalAlpha = style.opacity;
+ ctx.direction = style.textDirection;
+
+ if (style.backgroundColor !== 'transparent') {
+ const padding = style.backgroundPadding;
+ ctx.fillStyle = style.backgroundColor;
+ ctx.fillRect(
+ drawX - padding,
+ currentY - padding,
+ run.width + padding * 2,
+ line.height + padding * 2
+ );
+ }
+
+ if (style.shadowColor !== 'transparent' && style.shadowBlur > 0) {
+ ctx.shadowColor = style.shadowColor;
+ ctx.shadowBlur = style.shadowBlur;
+ ctx.shadowOffsetX = style.shadowOffsetX;
+ ctx.shadowOffsetY = style.shadowOffsetY;
+ }
+
+ if (style.strokeWidth > 0 && style.strokeColor !== 'transparent') {
+ ctx.strokeStyle = style.strokeColor;
+ ctx.lineWidth = style.strokeWidth;
+ ctx.lineJoin = 'round';
+
+ if (style.letterSpacing !== 0) {
+ let charX = drawX;
+ for (const char of displayText) {
+ ctx.strokeText(char, charX, drawY);
+ charX += ctx.measureText(char).width + style.letterSpacing;
+ }
+ } else {
+ ctx.strokeText(displayText, drawX, drawY);
+ }
+ }
+
+ ctx.fillStyle = style.color;
+ ctx.shadowColor = 'transparent';
+ ctx.shadowBlur = 0;
+ ctx.shadowOffsetX = 0;
+ ctx.shadowOffsetY = 0;
+
+ if (style.letterSpacing !== 0) {
+ let charX = drawX;
+ for (const char of displayText) {
+ ctx.fillText(char, charX, drawY);
+ charX += ctx.measureText(char).width + style.letterSpacing;
+ }
+ } else {
+ ctx.fillText(displayText, drawX, drawY);
+ }
+
+ if (style.textDecoration !== 'none') {
+ ctx.strokeStyle = style.color;
+ ctx.lineWidth = Math.max(1, style.fontSize / 16);
+
+ if (style.textDecoration === 'underline' || style.textDecoration === 'both') {
+ const underlineY = drawY + style.fontSize * 0.15;
+ ctx.beginPath();
+ ctx.moveTo(drawX, underlineY);
+ ctx.lineTo(drawX + run.width, underlineY);
+ ctx.stroke();
+ }
+
+ if (style.textDecoration === 'strikethrough' || style.textDecoration === 'both') {
+ const strikeY = drawY - style.fontSize * 0.3;
+ ctx.beginPath();
+ ctx.moveTo(drawX, strikeY);
+ ctx.lineTo(drawX + run.width, strikeY);
+ ctx.stroke();
+ }
+ }
+ }
+
+ currentY += line.height;
+ }
+
+ ctx.restore();
+}
+
+export function createTextDocument(
+ text: string,
+ style?: Partial<TextStyle>,
+ boundingBox?: { width: number; height: number }
+): TextDocument {
+ const paragraphs = text.split('\n').map((paragraphText) => ({
+ text: paragraphText,
+ runs: [],
+ alignment: (style?.textAlign || 'left') as TextAlignment,
+ indent: 0,
+ spaceBefore: 0,
+ spaceAfter: 0,
+ }));
+
+ return {
+ paragraphs,
+ defaultStyle: { ...DEFAULT_TEXT_STYLE, ...style },
+ boundingBox: boundingBox || null,
+ wrapMode: boundingBox ? 'word' : 'none',
+ };
+}
+
+export function textOnPath(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ text: string,
+ style: TextStyle,
+ _path: Path2D,
+ pathLength: number,
+ startOffset: number = 0,
+ spacing: number = 0
+): void {
+ ctx.save();
+ ctx.font = buildFontString(style);
+ ctx.fillStyle = style.color;
+ ctx.globalAlpha = style.opacity;
+
+ const chars = applyTextCase(text, style.textCase).split('');
+ let currentOffset = startOffset;
+
+ const canvas = ctx.canvas as HTMLCanvasElement;
+ const tempCtx = canvas.getContext('2d');
+ if (!tempCtx) {
+ ctx.restore();
+ return;
+ }
+
+ const step = 0.5;
+ const pathPoints: Array<{ x: number; y: number; angle: number }> = [];
+
+ for (let t = 0; t <= pathLength; t += step) {
+ const fraction = t / pathLength;
+ pathPoints.push({
+ x: fraction * canvas.width,
+ y: canvas.height / 2,
+ angle: 0,
+ });
+ }
+
+ for (const char of chars) {
+ const charWidth = ctx.measureText(char).width + style.letterSpacing + spacing;
+
+ if (currentOffset >= pathLength) break;
+
+ const pointIndex = Math.min(
+ Math.floor((currentOffset / pathLength) * pathPoints.length),
+ pathPoints.length - 1
+ );
+ const point = pathPoints[pointIndex];
+
+ ctx.save();
+ ctx.translate(point.x, point.y);
+ ctx.rotate(point.angle);
+ ctx.fillText(char, 0, 0);
+ ctx.restore();
+
+ currentOffset += charWidth;
+ }
+
+ ctx.restore();
+}
diff --git a/apps/image/src/tools/vector/path-operations.ts b/apps/image/src/tools/vector/path-operations.ts
new file mode 100644
index 00000000..2ed9862a
--- /dev/null
+++ b/apps/image/src/tools/vector/path-operations.ts
@@ -0,0 +1,549 @@
+import { VectorPath, BezierPoint, pathToPath2D, createPath, createBezierPoint } from './pen-tool';
+
+export type PathOperation = 'union' | 'subtract' | 'intersect' | 'exclude';
+
+export interface PathBounds {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+export function getPathBounds(path: VectorPath): PathBounds {
+ const { points } = path;
+
+ if (points.length === 0) {
+ return { x: 0, y: 0, width: 0, height: 0 };
+ }
+
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+
+ for (const point of points) {
+ minX = Math.min(minX, point.x);
+ minY = Math.min(minY, point.y);
+ maxX = Math.max(maxX, point.x);
+ maxY = Math.max(maxY, point.y);
+
+ if (point.handleIn) {
+ minX = Math.min(minX, point.handleIn.x);
+ minY = Math.min(minY, point.handleIn.y);
+ maxX = Math.max(maxX, point.handleIn.x);
+ maxY = Math.max(maxY, point.handleIn.y);
+ }
+
+ if (point.handleOut) {
+ minX = Math.min(minX, point.handleOut.x);
+ minY = Math.min(minY, point.handleOut.y);
+ maxX = Math.max(maxX, point.handleOut.x);
+ maxY = Math.max(maxY, point.handleOut.y);
+ }
+ }
+
+ return {
+ x: minX,
+ y: minY,
+ width: maxX - minX,
+ height: maxY - minY,
+ };
+}
+
+export function translatePath(path: VectorPath, dx: number, dy: number): VectorPath {
+ const newPoints: BezierPoint[] = path.points.map((point) => ({
+ ...point,
+ x: point.x + dx,
+ y: point.y + dy,
+ handleIn: point.handleIn
+ ? { x: point.handleIn.x + dx, y: point.handleIn.y + dy }
+ : null,
+ handleOut: point.handleOut
+ ? { x: point.handleOut.x + dx, y: point.handleOut.y + dy }
+ : null,
+ }));
+
+ return { ...path, points: newPoints };
+}
+
+export function scalePath(
+ path: VectorPath,
+ scaleX: number,
+ scaleY: number,
+ originX?: number,
+ originY?: number
+): VectorPath {
+ const bounds = getPathBounds(path);
+ const ox = originX ?? bounds.x + bounds.width / 2;
+ const oy = originY ?? bounds.y + bounds.height / 2;
+
+ const newPoints: BezierPoint[] = path.points.map((point) => ({
+ ...point,
+ x: ox + (point.x - ox) * scaleX,
+ y: oy + (point.y - oy) * scaleY,
+ handleIn: point.handleIn
+ ? {
+ x: ox + (point.handleIn.x - ox) * scaleX,
+ y: oy + (point.handleIn.y - oy) * scaleY,
+ }
+ : null,
+ handleOut: point.handleOut
+ ? {
+ x: ox + (point.handleOut.x - ox) * scaleX,
+ y: oy + (point.handleOut.y - oy) * scaleY,
+ }
+ : null,
+ }));
+
+ return { ...path, points: newPoints };
+}
+
+export function rotatePath(
+ path: VectorPath,
+ angle: number,
+ originX?: number,
+ originY?: number
+): VectorPath {
+ const bounds = getPathBounds(path);
+ const ox = originX ?? bounds.x + bounds.width / 2;
+ const oy = originY ?? bounds.y + bounds.height / 2;
+
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+
+ const rotatePoint = (x: number, y: number) => ({
+ x: ox + (x - ox) * cos - (y - oy) * sin,
+ y: oy + (x - ox) * sin + (y - oy) * cos,
+ });
+
+ const newPoints: BezierPoint[] = path.points.map((point) => {
+ const rotated = rotatePoint(point.x, point.y);
+ return {
+ ...point,
+ ...rotated,
+ handleIn: point.handleIn ? rotatePoint(point.handleIn.x, point.handleIn.y) : null,
+ handleOut: point.handleOut ? rotatePoint(point.handleOut.x, point.handleOut.y) : null,
+ };
+ });
+
+ return { ...path, points: newPoints };
+}
+
+export function flipPathHorizontal(path: VectorPath, originX?: number): VectorPath {
+ const bounds = getPathBounds(path);
+ const ox = originX ?? bounds.x + bounds.width / 2;
+
+ const newPoints: BezierPoint[] = path.points.map((point) => ({
+ ...point,
+ x: ox * 2 - point.x,
+ handleIn: point.handleIn
+ ? { x: ox * 2 - point.handleIn.x, y: point.handleIn.y }
+ : null,
+ handleOut: point.handleOut
+ ? { x: ox * 2 - point.handleOut.x, y: point.handleOut.y }
+ : null,
+ }));
+
+ return { ...path, points: newPoints.reverse() };
+}
+
+export function flipPathVertical(path: VectorPath, originY?: number): VectorPath {
+ const bounds = getPathBounds(path);
+ const oy = originY ?? bounds.y + bounds.height / 2;
+
+ const newPoints: BezierPoint[] = path.points.map((point) => ({
+ ...point,
+ y: oy * 2 - point.y,
+ handleIn: point.handleIn
+ ? { x: point.handleIn.x, y: oy * 2 - point.handleIn.y }
+ : null,
+ handleOut: point.handleOut
+ ? { x: point.handleOut.x, y: oy * 2 - point.handleOut.y }
+ : null,
+ }));
+
+ return { ...path, points: newPoints.reverse() };
+}
+
+export function reversePath(path: VectorPath): VectorPath {
+ const newPoints: BezierPoint[] = path.points
+ .slice()
+ .reverse()
+ .map((point) => ({
+ ...point,
+ handleIn: point.handleOut,
+ handleOut: point.handleIn,
+ }));
+
+ return { ...path, points: newPoints };
+}
+
+export function offsetPath(path: VectorPath, distance: number): VectorPath {
+ const { points, closed } = path;
+ if (points.length < 2) return path;
+
+ const newPoints: BezierPoint[] = [];
+
+ for (let i = 0; i < points.length; i++) {
+ const current = points[i];
+ const prev = points[(i - 1 + points.length) % points.length];
+ const next = points[(i + 1) % points.length];
+
+ const toPrev = { x: prev.x - current.x, y: prev.y - current.y };
+ const toNext = { x: next.x - current.x, y: next.y - current.y };
+
+ const prevLen = Math.hypot(toPrev.x, toPrev.y);
+ const nextLen = Math.hypot(toNext.x, toNext.y);
+
+ if (prevLen === 0 || nextLen === 0) {
+ newPoints.push(current);
+ continue;
+ }
+
+ const normPrev = { x: toPrev.x / prevLen, y: toPrev.y / prevLen };
+ const normNext = { x: toNext.x / nextLen, y: toNext.y / nextLen };
+
+ const perpPrev = { x: -normPrev.y, y: normPrev.x };
+ const perpNext = { x: -normNext.y, y: normNext.x };
+
+ const bisector = {
+ x: (perpPrev.x + perpNext.x) / 2,
+ y: (perpPrev.y + perpNext.y) / 2,
+ };
+
+ const bisectorLen = Math.hypot(bisector.x, bisector.y);
+ if (bisectorLen === 0) {
+ newPoints.push(current);
+ continue;
+ }
+
+ const cross = normPrev.x * normNext.y - normPrev.y * normNext.x;
+ const dot = normPrev.x * normNext.x + normPrev.y * normNext.y;
+ const halfAngle = Math.acos(Math.max(-1, Math.min(1, dot))) / 2;
+ const miterLength = distance / Math.cos(halfAngle);
+
+ const sign = cross >= 0 ? 1 : -1;
+ const offsetX = (bisector.x / bisectorLen) * miterLength * sign;
+ const offsetY = (bisector.y / bisectorLen) * miterLength * sign;
+
+ newPoints.push({
+ ...current,
+ x: current.x + offsetX,
+ y: current.y + offsetY,
+ handleIn: current.handleIn
+ ? { x: current.handleIn.x + offsetX, y: current.handleIn.y + offsetY }
+ : null,
+ handleOut: current.handleOut
+ ? { x: current.handleOut.x + offsetX, y: current.handleOut.y + offsetY }
+ : null,
+ });
+ }
+
+ if (!closed && points.length >= 2) {
+ const first = points[0];
+ const second = points[1];
+ const toSecond = { x: second.x - first.x, y: second.y - first.y };
+ const len = Math.hypot(toSecond.x, toSecond.y);
+ if (len > 0) {
+ const perp = { x: -toSecond.y / len, y: toSecond.x / len };
+ newPoints[0] = {
+ ...newPoints[0],
+ x: first.x + perp.x * distance,
+ y: first.y + perp.y * distance,
+ };
+ }
+
+ const last = points[points.length - 1];
+ const secondLast = points[points.length - 2];
+ const toSecondLast = { x: secondLast.x - last.x, y: secondLast.y - last.y };
+ const lastLen = Math.hypot(toSecondLast.x, toSecondLast.y);
+ if (lastLen > 0) {
+ const perp = { x: toSecondLast.y / lastLen, y: -toSecondLast.x / lastLen };
+ newPoints[newPoints.length - 1] = {
+ ...newPoints[newPoints.length - 1],
+ x: last.x + perp.x * distance,
+ y: last.y + perp.y * distance,
+ };
+ }
+ }
+
+ return { ...path, points: newPoints };
+}
+
+export function combinePaths(
+ pathA: VectorPath,
+ pathB: VectorPath,
+ operation: PathOperation,
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D
+): VectorPath {
+ const path2dA = pathToPath2D(pathA);
+ const path2dB = pathToPath2D(pathB);
+
+ const boundsA = getPathBounds(pathA);
+ const boundsB = getPathBounds(pathB);
+
+ const minX = Math.min(boundsA.x, boundsB.x);
+ const minY = Math.min(boundsA.y, boundsB.y);
+ const maxX = Math.max(boundsA.x + boundsA.width, boundsB.x + boundsB.width);
+ const maxY = Math.max(boundsA.y + boundsA.height, boundsB.y + boundsB.height);
+
+ const samplePoints: Array<{ x: number; y: number }> = [];
+ const step = 5;
+
+ for (let x = minX; x <= maxX; x += step) {
+ for (let y = minY; y <= maxY; y += step) {
+ const inA = ctx.isPointInPath(path2dA, x, y);
+ const inB = ctx.isPointInPath(path2dB, x, y);
+
+ let include = false;
+ switch (operation) {
+ case 'union':
+ include = inA || inB;
+ break;
+ case 'subtract':
+ include = inA && !inB;
+ break;
+ case 'intersect':
+ include = inA && inB;
+ break;
+ case 'exclude':
+ include = (inA && !inB) || (!inA && inB);
+ break;
+ }
+
+ if (include) {
+ samplePoints.push({ x, y });
+ }
+ }
+ }
+
+ const contourPoints = findContourPoints(samplePoints, step);
+
+ const resultPath = createPath({
+ fillColor: pathA.fillColor,
+ fillOpacity: pathA.fillOpacity,
+ strokeColor: pathA.strokeColor,
+ strokeWidth: pathA.strokeWidth,
+ });
+
+ resultPath.points = contourPoints.map((p) =>
+ createBezierPoint(p.x, p.y, 'corner')
+ );
+ resultPath.closed = true;
+
+ return resultPath;
+}
+
+function findContourPoints(
+ points: Array<{ x: number; y: number }>,
+ gridSize: number
+): Array<{ x: number; y: number }> {
+ if (points.length === 0) return [];
+
+ const pointSet = new Set(points.map((p) => `${Math.round(p.x)},${Math.round(p.y)}`));
+
+ const boundary: Array<{ x: number; y: number }> = [];
+
+ for (const point of points) {
+ const x = Math.round(point.x);
+ const y = Math.round(point.y);
+
+ const neighbors = [
+ [x - gridSize, y],
+ [x + gridSize, y],
+ [x, y - gridSize],
+ [x, y + gridSize],
+ ];
+
+ const isBoundary = neighbors.some((n) => !pointSet.has(`${n[0]},${n[1]}`));
+
+ if (isBoundary) {
+ boundary.push({ x, y });
+ }
+ }
+
+ if (boundary.length === 0) return points.slice(0, 1);
+
+ return orderBoundaryPoints(boundary, gridSize);
+}
+
+function orderBoundaryPoints(
+ points: Array<{ x: number; y: number }>,
+ gridSize: number
+): Array<{ x: number; y: number }> {
+ if (points.length <= 2) return points;
+
+ const ordered: Array<{ x: number; y: number }> = [];
+ const remaining = new Set(points.map((_, i) => i));
+
+ let currentIdx = 0;
+ remaining.delete(currentIdx);
+ ordered.push(points[currentIdx]);
+
+ while (remaining.size > 0) {
+ const current = points[currentIdx];
+ let closestIdx = -1;
+ let closestDist = Infinity;
+
+ for (const idx of remaining) {
+ const dist = Math.hypot(points[idx].x - current.x, points[idx].y - current.y);
+ if (dist < closestDist) {
+ closestDist = dist;
+ closestIdx = idx;
+ }
+ }
+
+ if (closestIdx === -1 || closestDist > gridSize * 2) break;
+
+ remaining.delete(closestIdx);
+ ordered.push(points[closestIdx]);
+ currentIdx = closestIdx;
+ }
+
+ return ordered;
+}
+
+export function pathToSVG(path: VectorPath): string {
+ const { points, closed } = path;
+
+ if (points.length === 0) return '';
+
+ let d = `M ${points[0].x} ${points[0].y}`;
+
+ for (let i = 0; i < points.length - 1; i++) {
+ const current = points[i];
+ const next = points[i + 1];
+
+ const cp1 = current.handleOut || current;
+ const cp2 = next.handleIn || next;
+
+ d += ` C ${cp1.x} ${cp1.y}, ${cp2.x} ${cp2.y}, ${next.x} ${next.y}`;
+ }
+
+ if (closed && points.length > 1) {
+ const last = points[points.length - 1];
+ const first = points[0];
+ const cp1 = last.handleOut || last;
+ const cp2 = first.handleIn || first;
+
+ d += ` C ${cp1.x} ${cp1.y}, ${cp2.x} ${cp2.y}, ${first.x} ${first.y}`;
+ d += ' Z';
+ }
+
+ return d;
+}
+
+export function svgToPath(svgPath: string): VectorPath {
+ const path = createPath();
+ const commands = svgPath.match(/[MmLlHhVvCcSsQqTtAaZz][^MmLlHhVvCcSsQqTtAaZz]*/g);
+
+ if (!commands) return path;
+
+ let currentX = 0;
+ let currentY = 0;
+ let startX = 0;
+ let startY = 0;
+
+ for (const command of commands) {
+ const type = command[0];
+ const args = command
+ .slice(1)
+ .trim()
+ .split(/[\s,]+/)
+ .map(parseFloat)
+ .filter((n) => !isNaN(n));
+
+ switch (type) {
+ case 'M':
+ currentX = args[0];
+ currentY = args[1];
+ startX = currentX;
+ startY = currentY;
+ path.points.push(createBezierPoint(currentX, currentY, 'corner'));
+ break;
+
+ case 'm':
+ currentX += args[0];
+ currentY += args[1];
+ startX = currentX;
+ startY = currentY;
+ path.points.push(createBezierPoint(currentX, currentY, 'corner'));
+ break;
+
+ case 'L':
+ currentX = args[0];
+ currentY = args[1];
+ path.points.push(createBezierPoint(currentX, currentY, 'corner'));
+ break;
+
+ case 'l':
+ currentX += args[0];
+ currentY += args[1];
+ path.points.push(createBezierPoint(currentX, currentY, 'corner'));
+ break;
+
+ case 'H':
+ currentX = args[0];
+ path.points.push(createBezierPoint(currentX, currentY, 'corner'));
+ break;
+
+ case 'h':
+ currentX += args[0];
+ path.points.push(createBezierPoint(currentX, currentY, 'corner'));
+ break;
+
+ case 'V':
+ currentY = args[0];
+ path.points.push(createBezierPoint(currentX, currentY, 'corner'));
+ break;
+
+ case 'v':
+ currentY += args[0];
+ path.points.push(createBezierPoint(currentX, currentY, 'corner'));
+ break;
+
+ case 'C': {
+ const lastPoint = path.points[path.points.length - 1];
+ if (lastPoint) {
+ lastPoint.handleOut = { x: args[0], y: args[1] };
+ }
+ const newPoint = createBezierPoint(args[4], args[5], 'smooth');
+ newPoint.handleIn = { x: args[2], y: args[3] };
+ path.points.push(newPoint);
+ currentX = args[4];
+ currentY = args[5];
+ break;
+ }
+
+ case 'c': {
+ const lastPoint = path.points[path.points.length - 1];
+ if (lastPoint) {
+ lastPoint.handleOut = { x: currentX + args[0], y: currentY + args[1] };
+ }
+ const newPoint = createBezierPoint(currentX + args[4], currentY + args[5], 'smooth');
+ newPoint.handleIn = { x: currentX + args[2], y: currentY + args[3] };
+ path.points.push(newPoint);
+ currentX += args[4];
+ currentY += args[5];
+ break;
+ }
+
+ case 'Z':
+ case 'z':
+ path.closed = true;
+ currentX = startX;
+ currentY = startY;
+ break;
+ }
+ }
+
+ return path;
+}
+
+export function duplicatePath(path: VectorPath, offsetX: number = 10, offsetY: number = 10): VectorPath {
+ const duplicate = translatePath(path, offsetX, offsetY);
+ return {
+ ...duplicate,
+ id: `${path.id}_copy_${Date.now()}`,
+ };
+}
diff --git a/apps/image/src/tools/vector/pen-tool.ts b/apps/image/src/tools/vector/pen-tool.ts
new file mode 100644
index 00000000..cc694738
--- /dev/null
+++ b/apps/image/src/tools/vector/pen-tool.ts
@@ -0,0 +1,518 @@
+export interface BezierPoint {
+ x: number;
+ y: number;
+ handleIn: { x: number; y: number } | null;
+ handleOut: { x: number; y: number } | null;
+ type: 'corner' | 'smooth' | 'symmetric';
+}
+
+export interface VectorPath {
+ id: string;
+ points: BezierPoint[];
+ closed: boolean;
+ fillColor: string;
+ fillOpacity: number;
+ strokeColor: string;
+ strokeWidth: number;
+ strokeOpacity: number;
+ strokeDash: number[];
+ strokeLineCap: CanvasLineCap;
+ strokeLineJoin: CanvasLineJoin;
+}
+
+export interface PenToolState {
+ currentPath: VectorPath | null;
+ isDrawing: boolean;
+ selectedPointIndex: number | null;
+ selectedHandleType: 'in' | 'out' | null;
+ previewPoint: { x: number; y: number } | null;
+}
+
+export const DEFAULT_PATH_STYLE = {
+ fillColor: 'transparent',
+ fillOpacity: 1,
+ strokeColor: '#000000',
+ strokeWidth: 2,
+ strokeOpacity: 1,
+ strokeDash: [] as number[],
+ strokeLineCap: 'round' as CanvasLineCap,
+ strokeLineJoin: 'round' as CanvasLineJoin,
+};
+
+let pathIdCounter = 0;
+
+export function createPath(style?: Partial<typeof DEFAULT_PATH_STYLE>): VectorPath {
+ return {
+ id: `path_${++pathIdCounter}_${Date.now()}`,
+ points: [],
+ closed: false,
+ ...DEFAULT_PATH_STYLE,
+ ...style,
+ };
+}
+
+export function createBezierPoint(
+ x: number,
+ y: number,
+ type: BezierPoint['type'] = 'smooth'
+): BezierPoint {
+ return {
+ x,
+ y,
+ handleIn: null,
+ handleOut: null,
+ type,
+ };
+}
+
+export function addPointToPath(
+ path: VectorPath,
+ point: BezierPoint
+): VectorPath {
+ return {
+ ...path,
+ points: [...path.points, point],
+ };
+}
+
+export function updatePointInPath(
+ path: VectorPath,
+ index: number,
+ updates: Partial<BezierPoint>
+): VectorPath {
+ if (index < 0 || index >= path.points.length) return path;
+
+ const newPoints = [...path.points];
+ newPoints[index] = { ...newPoints[index], ...updates };
+
+ return { ...path, points: newPoints };
+}
+
+export function removePointFromPath(path: VectorPath, index: number): VectorPath {
+ if (index < 0 || index >= path.points.length) return path;
+
+ return {
+ ...path,
+ points: path.points.filter((_, i) => i !== index),
+ };
+}
+
+export function closePath(path: VectorPath): VectorPath {
+ return { ...path, closed: true };
+}
+
+export function setPointHandles(
+ point: BezierPoint,
+ handleOut: { x: number; y: number } | null,
+ handleIn?: { x: number; y: number } | null
+): BezierPoint {
+ const updated = { ...point, handleOut };
+
+ if (handleIn !== undefined) {
+ updated.handleIn = handleIn;
+ } else if (point.type === 'symmetric' && handleOut) {
+ updated.handleIn = {
+ x: point.x - (handleOut.x - point.x),
+ y: point.y - (handleOut.y - point.y),
+ };
+ } else if (point.type === 'smooth' && handleOut && point.handleIn) {
+ const inDist = Math.hypot(point.handleIn.x - point.x, point.handleIn.y - point.y);
+ const angle = Math.atan2(point.y - handleOut.y, point.x - handleOut.x);
+ updated.handleIn = {
+ x: point.x + Math.cos(angle) * inDist,
+ y: point.y + Math.sin(angle) * inDist,
+ };
+ }
+
+ return updated;
+}
+
+export function movePoint(
+ point: BezierPoint,
+ dx: number,
+ dy: number
+): BezierPoint {
+ return {
+ ...point,
+ x: point.x + dx,
+ y: point.y + dy,
+ handleIn: point.handleIn
+ ? { x: point.handleIn.x + dx, y: point.handleIn.y + dy }
+ : null,
+ handleOut: point.handleOut
+ ? { x: point.handleOut.x + dx, y: point.handleOut.y + dy }
+ : null,
+ };
+}
+
+function bezierCurve(
+ p0: { x: number; y: number },
+ p1: { x: number; y: number },
+ p2: { x: number; y: number },
+ p3: { x: number; y: number },
+ t: number
+): { x: number; y: number } {
+ const mt = 1 - t;
+ const mt2 = mt * mt;
+ const mt3 = mt2 * mt;
+ const t2 = t * t;
+ const t3 = t2 * t;
+
+ return {
+ x: mt3 * p0.x + 3 * mt2 * t * p1.x + 3 * mt * t2 * p2.x + t3 * p3.x,
+ y: mt3 * p0.y + 3 * mt2 * t * p1.y + 3 * mt * t2 * p2.y + t3 * p3.y,
+ };
+}
+
+export function pathToPath2D(vectorPath: VectorPath): Path2D {
+ const path = new Path2D();
+ const { points, closed } = vectorPath;
+
+ if (points.length === 0) return path;
+
+ path.moveTo(points[0].x, points[0].y);
+
+ for (let i = 0; i < points.length - 1; i++) {
+ const current = points[i];
+ const next = points[i + 1];
+
+ const cp1 = current.handleOut || { x: current.x, y: current.y };
+ const cp2 = next.handleIn || { x: next.x, y: next.y };
+
+ path.bezierCurveTo(cp1.x, cp1.y, cp2.x, cp2.y, next.x, next.y);
+ }
+
+ if (closed && points.length > 1) {
+ const last = points[points.length - 1];
+ const first = points[0];
+
+ const cp1 = last.handleOut || { x: last.x, y: last.y };
+ const cp2 = first.handleIn || { x: first.x, y: first.y };
+
+ path.bezierCurveTo(cp1.x, cp1.y, cp2.x, cp2.y, first.x, first.y);
+ path.closePath();
+ }
+
+ return path;
+}
+
+export function renderPath(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ vectorPath: VectorPath
+): void {
+ const path2d = pathToPath2D(vectorPath);
+
+ ctx.save();
+
+ if (vectorPath.fillColor !== 'transparent') {
+ ctx.fillStyle = vectorPath.fillColor;
+ ctx.globalAlpha = vectorPath.fillOpacity;
+ ctx.fill(path2d);
+ }
+
+ if (vectorPath.strokeWidth > 0 && vectorPath.strokeColor !== 'transparent') {
+ ctx.strokeStyle = vectorPath.strokeColor;
+ ctx.lineWidth = vectorPath.strokeWidth;
+ ctx.lineCap = vectorPath.strokeLineCap;
+ ctx.lineJoin = vectorPath.strokeLineJoin;
+ ctx.globalAlpha = vectorPath.strokeOpacity;
+ ctx.setLineDash(vectorPath.strokeDash);
+ ctx.stroke(path2d);
+ ctx.setLineDash([]);
+ }
+
+ ctx.restore();
+}
+
+export function renderPathHandles(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ vectorPath: VectorPath,
+ selectedIndex: number | null = null,
+ handleColor: string = '#0ea5e9',
+ pointColor: string = '#ffffff'
+): void {
+ const { points } = vectorPath;
+ const pointSize = 4;
+ const handleSize = 3;
+
+ ctx.save();
+
+ for (let i = 0; i < points.length; i++) {
+ const point = points[i];
+ const isSelected = i === selectedIndex;
+
+ if (point.handleIn) {
+ ctx.beginPath();
+ ctx.strokeStyle = handleColor;
+ ctx.lineWidth = 1;
+ ctx.moveTo(point.x, point.y);
+ ctx.lineTo(point.handleIn.x, point.handleIn.y);
+ ctx.stroke();
+
+ ctx.beginPath();
+ ctx.fillStyle = handleColor;
+ ctx.arc(point.handleIn.x, point.handleIn.y, handleSize, 0, Math.PI * 2);
+ ctx.fill();
+ }
+
+ if (point.handleOut) {
+ ctx.beginPath();
+ ctx.strokeStyle = handleColor;
+ ctx.lineWidth = 1;
+ ctx.moveTo(point.x, point.y);
+ ctx.lineTo(point.handleOut.x, point.handleOut.y);
+ ctx.stroke();
+
+ ctx.beginPath();
+ ctx.fillStyle = handleColor;
+ ctx.arc(point.handleOut.x, point.handleOut.y, handleSize, 0, Math.PI * 2);
+ ctx.fill();
+ }
+
+ ctx.beginPath();
+ ctx.fillStyle = isSelected ? handleColor : pointColor;
+ ctx.strokeStyle = handleColor;
+ ctx.lineWidth = 1.5;
+ ctx.rect(point.x - pointSize / 2, point.y - pointSize / 2, pointSize, pointSize);
+ ctx.fill();
+ ctx.stroke();
+ }
+
+ ctx.restore();
+}
+
+export function hitTestPath(
+ vectorPath: VectorPath,
+ x: number,
+ y: number,
+ threshold: number = 5
+): { type: 'point' | 'handleIn' | 'handleOut' | 'segment'; index: number } | null {
+ const { points } = vectorPath;
+
+ for (let i = 0; i < points.length; i++) {
+ const point = points[i];
+
+ if (Math.hypot(x - point.x, y - point.y) <= threshold) {
+ return { type: 'point', index: i };
+ }
+
+ if (point.handleIn && Math.hypot(x - point.handleIn.x, y - point.handleIn.y) <= threshold) {
+ return { type: 'handleIn', index: i };
+ }
+
+ if (point.handleOut && Math.hypot(x - point.handleOut.x, y - point.handleOut.y) <= threshold) {
+ return { type: 'handleOut', index: i };
+ }
+ }
+
+ for (let i = 0; i < points.length - 1; i++) {
+ if (isPointNearSegment(points[i], points[i + 1], x, y, threshold)) {
+ return { type: 'segment', index: i };
+ }
+ }
+
+ if (vectorPath.closed && points.length > 1) {
+ if (isPointNearSegment(points[points.length - 1], points[0], x, y, threshold)) {
+ return { type: 'segment', index: points.length - 1 };
+ }
+ }
+
+ return null;
+}
+
+function isPointNearSegment(
+ p1: BezierPoint,
+ p2: BezierPoint,
+ x: number,
+ y: number,
+ threshold: number
+): boolean {
+ const steps = 20;
+ const cp1 = p1.handleOut || { x: p1.x, y: p1.y };
+ const cp2 = p2.handleIn || { x: p2.x, y: p2.y };
+
+ for (let i = 0; i <= steps; i++) {
+ const t = i / steps;
+ const point = bezierCurve(p1, cp1, cp2, p2, t);
+
+ if (Math.hypot(x - point.x, y - point.y) <= threshold) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+export function getPathLength(vectorPath: VectorPath): number {
+ const { points, closed } = vectorPath;
+ if (points.length < 2) return 0;
+
+ let length = 0;
+ const steps = 50;
+
+ const segmentCount = closed ? points.length : points.length - 1;
+
+ for (let i = 0; i < segmentCount; i++) {
+ const p1 = points[i];
+ const p2 = points[(i + 1) % points.length];
+ const cp1 = p1.handleOut || { x: p1.x, y: p1.y };
+ const cp2 = p2.handleIn || { x: p2.x, y: p2.y };
+
+ let prevPoint = { x: p1.x, y: p1.y };
+ for (let j = 1; j <= steps; j++) {
+ const t = j / steps;
+ const point = bezierCurve(p1, cp1, cp2, p2, t);
+ length += Math.hypot(point.x - prevPoint.x, point.y - prevPoint.y);
+ prevPoint = point;
+ }
+ }
+
+ return length;
+}
+
+export function getPointAtLength(
+ vectorPath: VectorPath,
+ targetLength: number
+): { x: number; y: number; angle: number } | null {
+ const { points, closed } = vectorPath;
+ if (points.length < 2) return null;
+
+ let accumulatedLength = 0;
+ const steps = 50;
+
+ const segmentCount = closed ? points.length : points.length - 1;
+
+ for (let i = 0; i < segmentCount; i++) {
+ const p1 = points[i];
+ const p2 = points[(i + 1) % points.length];
+ const cp1 = p1.handleOut || { x: p1.x, y: p1.y };
+ const cp2 = p2.handleIn || { x: p2.x, y: p2.y };
+
+ let prevPoint = { x: p1.x, y: p1.y };
+ for (let j = 1; j <= steps; j++) {
+ const t = j / steps;
+ const point = bezierCurve(p1, cp1, cp2, p2, t);
+ const segmentLength = Math.hypot(point.x - prevPoint.x, point.y - prevPoint.y);
+
+ if (accumulatedLength + segmentLength >= targetLength) {
+ const ratio = (targetLength - accumulatedLength) / segmentLength;
+ const x = prevPoint.x + (point.x - prevPoint.x) * ratio;
+ const y = prevPoint.y + (point.y - prevPoint.y) * ratio;
+ const angle = Math.atan2(point.y - prevPoint.y, point.x - prevPoint.x);
+ return { x, y, angle };
+ }
+
+ accumulatedLength += segmentLength;
+ prevPoint = point;
+ }
+ }
+
+ const lastPoint = points[points.length - 1];
+ return { x: lastPoint.x, y: lastPoint.y, angle: 0 };
+}
+
+export function smoothPath(vectorPath: VectorPath, tension: number = 0.3): VectorPath {
+ const { points } = vectorPath;
+ if (points.length < 3) return vectorPath;
+
+ const newPoints: BezierPoint[] = points.map((point, i) => {
+ const prev = points[(i - 1 + points.length) % points.length];
+ const next = points[(i + 1) % points.length];
+
+ const dx = next.x - prev.x;
+ const dy = next.y - prev.y;
+
+ return {
+ ...point,
+ type: 'smooth' as const,
+ handleIn: {
+ x: point.x - dx * tension,
+ y: point.y - dy * tension,
+ },
+ handleOut: {
+ x: point.x + dx * tension,
+ y: point.y + dy * tension,
+ },
+ };
+ });
+
+ if (!vectorPath.closed) {
+ newPoints[0].handleIn = null;
+ newPoints[newPoints.length - 1].handleOut = null;
+ }
+
+ return { ...vectorPath, points: newPoints };
+}
+
+export function simplifyPath(vectorPath: VectorPath, tolerance: number = 2): VectorPath {
+ const { points } = vectorPath;
+ if (points.length <= 2) return vectorPath;
+
+ const simplified = ramerDouglasPeucker(
+ points.map((p) => ({ x: p.x, y: p.y })),
+ tolerance
+ );
+
+ const newPoints: BezierPoint[] = simplified.map((p) => ({
+ x: p.x,
+ y: p.y,
+ handleIn: null,
+ handleOut: null,
+ type: 'corner' as const,
+ }));
+
+ return smoothPath({ ...vectorPath, points: newPoints });
+}
+
+function ramerDouglasPeucker(
+ points: Array<{ x: number; y: number }>,
+ epsilon: number
+): Array<{ x: number; y: number }> {
+ if (points.length <= 2) return points;
+
+ let maxDist = 0;
+ let maxIndex = 0;
+ const start = points[0];
+ const end = points[points.length - 1];
+
+ for (let i = 1; i < points.length - 1; i++) {
+ const dist = perpendicularDistance(points[i], start, end);
+ if (dist > maxDist) {
+ maxDist = dist;
+ maxIndex = i;
+ }
+ }
+
+ if (maxDist > epsilon) {
+ const left = ramerDouglasPeucker(points.slice(0, maxIndex + 1), epsilon);
+ const right = ramerDouglasPeucker(points.slice(maxIndex), epsilon);
+ return [...left.slice(0, -1), ...right];
+ }
+
+ return [start, end];
+}
+
+function perpendicularDistance(
+ point: { x: number; y: number },
+ lineStart: { x: number; y: number },
+ lineEnd: { x: number; y: number }
+): number {
+ const dx = lineEnd.x - lineStart.x;
+ const dy = lineEnd.y - lineStart.y;
+ const len = Math.hypot(dx, dy);
+
+ if (len === 0) return Math.hypot(point.x - lineStart.x, point.y - lineStart.y);
+
+ const t = Math.max(
+ 0,
+ Math.min(
+ 1,
+ ((point.x - lineStart.x) * dx + (point.y - lineStart.y) * dy) / (len * len)
+ )
+ );
+
+ const projX = lineStart.x + t * dx;
+ const projY = lineStart.y + t * dy;
+
+ return Math.hypot(point.x - projX, point.y - projY);
+}
diff --git a/apps/image/src/tools/vector/shapes.ts b/apps/image/src/tools/vector/shapes.ts
new file mode 100644
index 00000000..b7e25d42
--- /dev/null
+++ b/apps/image/src/tools/vector/shapes.ts
@@ -0,0 +1,491 @@
+export type ShapeType =
+ | 'rectangle'
+ | 'roundedRect'
+ | 'ellipse'
+ | 'polygon'
+ | 'star'
+ | 'line'
+ | 'arrow'
+ | 'triangle'
+ | 'diamond'
+ | 'heart'
+ | 'cross'
+ | 'ring';
+
+export interface Point {
+ x: number;
+ y: number;
+}
+
+export interface ShapeStyle {
+ fillColor: string;
+ fillOpacity: number;
+ strokeColor: string;
+ strokeWidth: number;
+ strokeOpacity: number;
+ strokeDash: number[];
+ strokeLineCap: CanvasLineCap;
+ strokeLineJoin: CanvasLineJoin;
+ shadowColor: string;
+ shadowBlur: number;
+ shadowOffsetX: number;
+ shadowOffsetY: number;
+}
+
+export interface RectangleOptions {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ cornerRadius?: number | [number, number, number, number];
+}
+
+export interface EllipseOptions {
+ cx: number;
+ cy: number;
+ rx: number;
+ ry: number;
+ startAngle?: number;
+ endAngle?: number;
+}
+
+export interface PolygonOptions {
+ cx: number;
+ cy: number;
+ radius: number;
+ sides: number;
+ rotation?: number;
+}
+
+export interface StarOptions {
+ cx: number;
+ cy: number;
+ outerRadius: number;
+ innerRadius: number;
+ points: number;
+ rotation?: number;
+}
+
+export interface LineOptions {
+ x1: number;
+ y1: number;
+ x2: number;
+ y2: number;
+}
+
+export interface ArrowOptions extends LineOptions {
+ headLength?: number;
+ headWidth?: number;
+ doubleHead?: boolean;
+}
+
+export interface TriangleOptions {
+ cx: number;
+ cy: number;
+ size: number;
+ rotation?: number;
+}
+
+export const DEFAULT_SHAPE_STYLE: ShapeStyle = {
+ fillColor: '#3b82f6',
+ fillOpacity: 1,
+ strokeColor: '#1d4ed8',
+ strokeWidth: 2,
+ strokeOpacity: 1,
+ strokeDash: [],
+ strokeLineCap: 'round',
+ strokeLineJoin: 'round',
+ shadowColor: 'transparent',
+ shadowBlur: 0,
+ shadowOffsetX: 0,
+ shadowOffsetY: 0,
+};
+
+function applyStyle(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ style: Partial<ShapeStyle>
+): void {
+ const s = { ...DEFAULT_SHAPE_STYLE, ...style };
+
+ if (s.shadowColor !== 'transparent') {
+ ctx.shadowColor = s.shadowColor;
+ ctx.shadowBlur = s.shadowBlur;
+ ctx.shadowOffsetX = s.shadowOffsetX;
+ ctx.shadowOffsetY = s.shadowOffsetY;
+ }
+
+ if (s.fillColor !== 'transparent') {
+ ctx.fillStyle = s.fillColor;
+ ctx.globalAlpha = s.fillOpacity;
+ ctx.fill();
+ }
+
+ ctx.shadowColor = 'transparent';
+ ctx.shadowBlur = 0;
+ ctx.shadowOffsetX = 0;
+ ctx.shadowOffsetY = 0;
+
+ if (s.strokeWidth > 0 && s.strokeColor !== 'transparent') {
+ ctx.strokeStyle = s.strokeColor;
+ ctx.lineWidth = s.strokeWidth;
+ ctx.lineCap = s.strokeLineCap;
+ ctx.lineJoin = s.strokeLineJoin;
+ ctx.globalAlpha = s.strokeOpacity;
+ ctx.setLineDash(s.strokeDash);
+ ctx.stroke();
+ ctx.setLineDash([]);
+ }
+
+ ctx.globalAlpha = 1;
+}
+
+export function drawRectangle(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ options: RectangleOptions,
+ style?: Partial<ShapeStyle>
+): Path2D {
+ const { x, y, width, height, cornerRadius = 0 } = options;
+ const path = new Path2D();
+
+ if (cornerRadius === 0 || (Array.isArray(cornerRadius) && cornerRadius.every((r) => r === 0))) {
+ path.rect(x, y, width, height);
+ } else {
+ const radii = Array.isArray(cornerRadius)
+ ? cornerRadius
+ : [cornerRadius, cornerRadius, cornerRadius, cornerRadius];
+
+ const [tl, tr, br, bl] = radii.map((r) => Math.min(r, width / 2, height / 2));
+
+ path.moveTo(x + tl, y);
+ path.lineTo(x + width - tr, y);
+ path.arcTo(x + width, y, x + width, y + tr, tr);
+ path.lineTo(x + width, y + height - br);
+ path.arcTo(x + width, y + height, x + width - br, y + height, br);
+ path.lineTo(x + bl, y + height);
+ path.arcTo(x, y + height, x, y + height - bl, bl);
+ path.lineTo(x, y + tl);
+ path.arcTo(x, y, x + tl, y, tl);
+ path.closePath();
+ }
+
+ ctx.beginPath();
+ ctx.save();
+ applyStyle(ctx, style || {});
+ ctx.restore();
+
+ return path;
+}
+
+export function drawEllipse(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ options: EllipseOptions,
+ style?: Partial<ShapeStyle>
+): Path2D {
+ const { cx, cy, rx, ry, startAngle = 0, endAngle = Math.PI * 2 } = options;
+ const path = new Path2D();
+
+ path.ellipse(cx, cy, rx, ry, 0, startAngle, endAngle);
+ if (endAngle - startAngle < Math.PI * 2) {
+ path.lineTo(cx, cy);
+ path.closePath();
+ }
+
+ ctx.beginPath();
+ ctx.save();
+ applyStyle(ctx, style || {});
+ ctx.restore();
+
+ return path;
+}
+
+export function drawPolygon(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ options: PolygonOptions,
+ style?: Partial<ShapeStyle>
+): Path2D {
+ const { cx, cy, radius, sides, rotation = -Math.PI / 2 } = options;
+ const path = new Path2D();
+ const safeSides = Math.max(3, Math.round(sides));
+
+ const angleStep = (Math.PI * 2) / safeSides;
+
+ for (let i = 0; i <= safeSides; i++) {
+ const angle = rotation + i * angleStep;
+ const px = cx + radius * Math.cos(angle);
+ const py = cy + radius * Math.sin(angle);
+
+ if (i === 0) {
+ path.moveTo(px, py);
+ } else {
+ path.lineTo(px, py);
+ }
+ }
+ path.closePath();
+
+ ctx.beginPath();
+ ctx.save();
+ applyStyle(ctx, style || {});
+ ctx.restore();
+
+ return path;
+}
+
+export function drawStar(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ options: StarOptions,
+ style?: Partial<ShapeStyle>
+): Path2D {
+ const { cx, cy, outerRadius, innerRadius, points, rotation = -Math.PI / 2 } = options;
+ const path = new Path2D();
+ const safePoints = Math.max(3, Math.round(points));
+
+ const angleStep = Math.PI / safePoints;
+
+ for (let i = 0; i < safePoints * 2; i++) {
+ const angle = rotation + i * angleStep;
+ const radius = i % 2 === 0 ? outerRadius : innerRadius;
+ const px = cx + radius * Math.cos(angle);
+ const py = cy + radius * Math.sin(angle);
+
+ if (i === 0) {
+ path.moveTo(px, py);
+ } else {
+ path.lineTo(px, py);
+ }
+ }
+ path.closePath();
+
+ ctx.beginPath();
+ ctx.save();
+ applyStyle(ctx, style || {});
+ ctx.restore();
+
+ return path;
+}
+
+export function drawLine(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ options: LineOptions,
+ style?: Partial<ShapeStyle>
+): Path2D {
+ const { x1, y1, x2, y2 } = options;
+ const path = new Path2D();
+
+ path.moveTo(x1, y1);
+ path.lineTo(x2, y2);
+
+ ctx.beginPath();
+ ctx.save();
+ const lineStyle = { ...style, fillColor: 'transparent' };
+ applyStyle(ctx, lineStyle);
+ ctx.restore();
+
+ return path;
+}
+
+export function drawArrow(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ options: ArrowOptions,
+ style?: Partial<ShapeStyle>
+): Path2D {
+ const { x1, y1, x2, y2, headLength = 15, headWidth = 10, doubleHead = false } = options;
+ const path = new Path2D();
+
+ const angle = Math.atan2(y2 - y1, x2 - x1);
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+
+ if (doubleHead) {
+ const startX = x1 + headLength * cos;
+ const startY = y1 + headLength * sin;
+ path.moveTo(startX, startY);
+ } else {
+ path.moveTo(x1, y1);
+ }
+
+ const endX = x2 - headLength * cos;
+ const endY = y2 - headLength * sin;
+ path.lineTo(endX, endY);
+
+ path.moveTo(x2, y2);
+ path.lineTo(
+ x2 - headLength * cos + (headWidth / 2) * sin,
+ y2 - headLength * sin - (headWidth / 2) * cos
+ );
+ path.moveTo(x2, y2);
+ path.lineTo(
+ x2 - headLength * cos - (headWidth / 2) * sin,
+ y2 - headLength * sin + (headWidth / 2) * cos
+ );
+
+ if (doubleHead) {
+ path.moveTo(x1, y1);
+ path.lineTo(
+ x1 + headLength * cos + (headWidth / 2) * sin,
+ y1 + headLength * sin - (headWidth / 2) * cos
+ );
+ path.moveTo(x1, y1);
+ path.lineTo(
+ x1 + headLength * cos - (headWidth / 2) * sin,
+ y1 + headLength * sin + (headWidth / 2) * cos
+ );
+ }
+
+ ctx.beginPath();
+ ctx.save();
+ const arrowStyle = { ...style, fillColor: 'transparent' };
+ applyStyle(ctx, arrowStyle);
+ ctx.restore();
+
+ return path;
+}
+
+export function drawTriangle(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ options: TriangleOptions,
+ style?: Partial<ShapeStyle>
+): Path2D {
+ return drawPolygon(ctx, { ...options, radius: options.size, sides: 3 }, style);
+}
+
+export function drawDiamond(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ cx: number,
+ cy: number,
+ width: number,
+ height: number,
+ style?: Partial<ShapeStyle>
+): Path2D {
+ const path = new Path2D();
+
+ path.moveTo(cx, cy - height / 2);
+ path.lineTo(cx + width / 2, cy);
+ path.lineTo(cx, cy + height / 2);
+ path.lineTo(cx - width / 2, cy);
+ path.closePath();
+
+ ctx.beginPath();
+ ctx.save();
+ applyStyle(ctx, style || {});
+ ctx.restore();
+
+ return path;
+}
+
+export function drawHeart(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ cx: number,
+ cy: number,
+ size: number,
+ style?: Partial<ShapeStyle>
+): Path2D {
+ const path = new Path2D();
+ const width = size;
+ const height = size;
+ const topCurveHeight = height * 0.3;
+
+ path.moveTo(cx, cy + height / 2);
+ path.bezierCurveTo(
+ cx - width / 2,
+ cy + height / 4,
+ cx - width / 2,
+ cy - topCurveHeight,
+ cx,
+ cy - topCurveHeight
+ );
+ path.bezierCurveTo(
+ cx + width / 2,
+ cy - topCurveHeight,
+ cx + width / 2,
+ cy + height / 4,
+ cx,
+ cy + height / 2
+ );
+ path.closePath();
+
+ ctx.beginPath();
+ ctx.save();
+ applyStyle(ctx, style || {});
+ ctx.restore();
+
+ return path;
+}
+
+export function drawCross(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ cx: number,
+ cy: number,
+ size: number,
+ thickness: number,
+ style?: Partial<ShapeStyle>
+): Path2D {
+ const path = new Path2D();
+ const half = size / 2;
+ const t = thickness / 2;
+
+ path.moveTo(cx - t, cy - half);
+ path.lineTo(cx + t, cy - half);
+ path.lineTo(cx + t, cy - t);
+ path.lineTo(cx + half, cy - t);
+ path.lineTo(cx + half, cy + t);
+ path.lineTo(cx + t, cy + t);
+ path.lineTo(cx + t, cy + half);
+ path.lineTo(cx - t, cy + half);
+ path.lineTo(cx - t, cy + t);
+ path.lineTo(cx - half, cy + t);
+ path.lineTo(cx - half, cy - t);
+ path.lineTo(cx - t, cy - t);
+ path.closePath();
+
+ ctx.beginPath();
+ ctx.save();
+ applyStyle(ctx, style || {});
+ ctx.restore();
+
+ return path;
+}
+
+export function drawRing(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ cx: number,
+ cy: number,
+ outerRadius: number,
+ innerRadius: number,
+ style?: Partial<ShapeStyle>
+): Path2D {
+ const path = new Path2D();
+
+ path.arc(cx, cy, outerRadius, 0, Math.PI * 2);
+ path.moveTo(cx + innerRadius, cy);
+ path.arc(cx, cy, innerRadius, 0, Math.PI * 2, true);
+
+ ctx.beginPath();
+ ctx.save();
+ applyStyle(ctx, style || {});
+ ctx.restore();
+
+ return path;
+}
+
+export function getShapeBounds(_path: Path2D, _ctx: CanvasRenderingContext2D): DOMRect | null {
+ return null;
+}
+
+export function pointInShape(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ path: Path2D,
+ x: number,
+ y: number,
+ fillRule: CanvasFillRule = 'nonzero'
+): boolean {
+ return ctx.isPointInPath(path, x, y, fillRule);
+}
+
+export function strokeContainsPoint(
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ path: Path2D,
+ x: number,
+ y: number
+): boolean {
+ return ctx.isPointInStroke(path, x, y);
+}