Skip to content

AI-native design editor. Open-source Figma alternative.

fix(core): join the corners of a stroked vector path (#1147)

rcoenena39dd62f984d
diff --git a/changes/1147/fixed.md b/changes/1147/fixed.md
new file mode 100644
index 000000000..4914375da
--- /dev/null
+++ b/changes/1147/fixed.md
@@ -0,0 +1 @@
+- The corners of a stroked path take its join, as in Figma. This applies to paths drawn with the pen and to unfilled icons. Thick strokes no longer notch at each corner, and round or square caps appear only at the path's ends.
diff --git a/packages/core/src/canvas/renderer/visual-bounds.ts b/packages/core/src/canvas/renderer/visual-bounds.ts
index fe5223978..1cc4f34d6 100644
--- a/packages/core/src/canvas/renderer/visual-bounds.ts
+++ b/packages/core/src/canvas/renderer/visual-bounds.ts
@@ -8,7 +8,7 @@ import {
import Matrix from '@open-pencil/scene-graph/matrix'
export function worldNodeVisualBounds(graph: SceneGraph, node: SceneNode): VisualBounds {
- const stroke = strokeOverflow(node.strokes, node.strokeCap, node.vectorNetwork)
+ const stroke = strokeOverflow(node.strokes, node.strokeCap, node.vectorNetwork, node)
const effects = effectOverflow(node.effects)
const points = Matrix.mapPoints(getWorldMatrix(node, graph), [
-stroke - effects.left,
diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.ts
index 68d68b152..237c50988 100644
--- a/packages/core/src/canvas/scene.ts
+++ b/packages/core/src/canvas/scene.ts
@@ -15,7 +15,7 @@ import type { Color } from '@open-pencil/scene-graph/primitives'
import { createSceneGeometry, nodeOrientationMatrix, projectedNode } from '#core/geometry'
import { shownText } from '#core/text/case'
import { fontManager } from '#core/text/fonts'
-import { vectorNetworkToCenterlinePath } from '#core/vector'
+import { addStrokeRunToPath, strokeRuns, vectorNetworkToCenterlinePath } from '#core/vector'
import { figmaBlendModeToSkia, needsIsolatedBlendLayer } from './blend'
import { renderBooleanOperation } from './boolean'
@@ -656,32 +656,13 @@ function vectorStrokePaths(r: SkiaRenderer, node: SceneNode): Path[] | null {
const cached = r.vectorStrokePathCache.get(node.id)
if (cached) return cached
- const paths: Path[] = []
- for (const segment of node.vectorNetwork.segments) {
- const start = node.vectorNetwork.vertices[segment.start]
- const end = node.vectorNetwork.vertices[segment.end]
-
+ // A path per run, so the corners inside a run join and only its open ends take caps.
+ const { segments, vertices } = node.vectorNetwork
+ const paths = strokeRuns(segments).map((run) => {
const path = new r.ck.PathBuilder()
- path.moveTo(start.x, start.y)
- const isStraight =
- Math.abs(segment.tangentStart.x) < 0.001 &&
- Math.abs(segment.tangentStart.y) < 0.001 &&
- Math.abs(segment.tangentEnd.x) < 0.001 &&
- Math.abs(segment.tangentEnd.y) < 0.001
- if (isStraight) {
- path.lineTo(end.x, end.y)
- } else {
- path.cubicTo(
- start.x + segment.tangentStart.x,
- start.y + segment.tangentStart.y,
- end.x + segment.tangentEnd.x,
- end.y + segment.tangentEnd.y,
- end.x,
- end.y
- )
- }
- paths.push(path.detachAndDelete())
- }
+ addStrokeRunToPath(path, run, segments, vertices)
+ return path.detachAndDelete()
+ })
if (paths.length === 0) return null
r.vectorStrokePathCache.set(node.id, paths)
diff --git a/packages/core/src/figma-api/render-bounds.ts b/packages/core/src/figma-api/render-bounds.ts
index a89203337..9cf4b4cd2 100644
--- a/packages/core/src/figma-api/render-bounds.ts
+++ b/packages/core/src/figma-api/render-bounds.ts
@@ -85,7 +85,7 @@ function ownRenderBounds(node: SceneNode, graph: SceneGraph): VisualBounds | nul
if (!hasRenderableGeometry(node)) return null
const base = transformedRect(node, graph, 0, 0, node.width, node.height)
- const stroke = strokeOverflow(node.strokes, node.strokeCap, node.vectorNetwork)
+ const stroke = strokeOverflow(node.strokes, node.strokeCap, node.vectorNetwork, node)
let bounds = transformedRect(
node,
graph,
diff --git a/packages/core/src/tools/analyze/overlaps/helpers.ts b/packages/core/src/tools/analyze/overlaps/helpers.ts
index fec2746c3..d7f2622c2 100644
--- a/packages/core/src/tools/analyze/overlaps/helpers.ts
+++ b/packages/core/src/tools/analyze/overlaps/helpers.ts
@@ -278,7 +278,7 @@ function computeNodeVisualBounds(node: SceneNode, graph: SceneGraph): VisualBoun
// through the world matrix. Expanding the already-rotated AABB by `stroke`
// underestimates the stroked bounds for rotated nodes (the true stroked AABB
// grows by `stroke * (|cos θ| + |sin θ|)`, not `stroke`).
- const stroke = strokeOverflow(node.strokes, node.strokeCap, node.vectorNetwork)
+ const stroke = strokeOverflow(node.strokes, node.strokeCap, node.vectorNetwork, node)
const baseCorners = Matrix.mapPoints(matrix, [
-stroke,
-stroke,
diff --git a/packages/core/src/vector/index.ts b/packages/core/src/vector/index.ts
index 5ad6e4f60..4d236ee51 100644
--- a/packages/core/src/vector/index.ts
+++ b/packages/core/src/vector/index.ts
@@ -25,6 +25,7 @@ import type { VectorNetwork, WindingRule } from '@open-pencil/scene-graph'
import { addLoopToPath, addOpenSegmentsToPath } from './path-helpers'
export { vectorNetworkToCenterlinePath, fitCircleArc, isClosedThinCrescent } from './centerline'
export { regenerateFillGeometry } from './fill-geometry'
+export { addStrokeRunToPath, strokeRuns, type StrokeRun } from './path-helpers'
export function vectorNetworkToPath(ck: CanvasKit, network: VectorNetwork): Path[] {
const { vertices, segments, regions } = network
diff --git a/packages/core/src/vector/path-helpers.ts b/packages/core/src/vector/path-helpers.ts
index c24e91680..c7508d239 100644
--- a/packages/core/src/vector/path-helpers.ts
+++ b/packages/core/src/vector/path-helpers.ts
@@ -147,3 +147,82 @@ export function buildChains(segments: VectorSegment[]): number[][] {
return chains
}
+
+/** A stretch of a network's segments stroked as one contour, so its corners join. */
+export interface StrokeRun {
+ /** The vertex the run starts at. */
+ start: number
+ /** Segment indices in drawing order. */
+ segments: number[]
+ /** Whether the run comes back to its start, joining there instead of taking caps. */
+ closed: boolean
+}
+
+/**
+ * Segments chained into runs as Figma strokes a network: a run passes through every vertex
+ * exactly two segments meet at, so its corners take the stroke's join and only its open ends take
+ * caps. Runs stop at open ends and at junctions where three or more segments meet.
+ */
+export function strokeRuns(segments: VectorSegment[]): StrokeRun[] {
+ const incident = new Map<number, number[]>()
+ const meet = (vertex: number, index: number) => {
+ const list = incident.get(vertex)
+ if (list) list.push(index)
+ else incident.set(vertex, [index])
+ }
+ for (const [index, segment] of segments.entries()) {
+ meet(segment.start, index)
+ if (segment.end !== segment.start) meet(segment.end, index)
+ }
+ const used = new Set<number>()
+ const across = (index: number, vertex: number) =>
+ segments[index].start === vertex ? segments[index].end : segments[index].start
+ /** Extends a run through `vertex` for as long as two segments meet at each vertex reached. */
+ const extend = (vertex: number, from: number, add: (index: number) => void) => {
+ for (;;) {
+ const meeting = incident.get(vertex)
+ if (meeting?.length !== 2) return vertex
+ const next = meeting[0] === from ? meeting[1] : meeting[0]
+ if (used.has(next)) return vertex
+ used.add(next)
+ add(next)
+ vertex = across(next, vertex)
+ from = next
+ }
+ }
+
+ const runs: StrokeRun[] = []
+ for (const [first, segment] of segments.entries()) {
+ if (used.has(first)) continue
+ used.add(first)
+ const run = [first]
+ const end = extend(segment.end, first, (index) => run.push(index))
+ if (end === segment.start) {
+ runs.push({ start: segment.start, segments: run, closed: true })
+ continue
+ }
+ const start = extend(segment.start, first, (index) => run.unshift(index))
+ // A loop through a junction stops at it from both sides; it still closes there, whichever
+ // of its segments is stored first.
+ runs.push({ start, segments: run, closed: start === end })
+ }
+ return runs
+}
+
+/** Emits a stroke run as one contour, closed when the run comes back to its start. */
+export function addStrokeRunToPath(
+ path: PathSink,
+ run: StrokeRun,
+ segments: VectorSegment[],
+ vertices: VectorVertex[]
+): void {
+ let current = run.start
+ path.moveTo(vertices[current].x, vertices[current].y)
+ for (const index of run.segments) {
+ const segment = segments[index]
+ const forward = segment.start === current
+ addSegmentDirected(path, segment, vertices, forward)
+ current = forward ? segment.end : segment.start
+ }
+ if (run.closed) path.close()
+}
diff --git a/packages/core/tests/canvas/vector-stroke-joins.test.ts b/packages/core/tests/canvas/vector-stroke-joins.test.ts
new file mode 100644
index 000000000..f0b6041e8
--- /dev/null
+++ b/packages/core/tests/canvas/vector-stroke-joins.test.ts
@@ -0,0 +1,98 @@
+import { afterAll, describe, expect, test } from 'bun:test'
+
+import { SkiaRenderer } from '@open-pencil/core'
+import { initCanvasKit, renderNodesToImage } from '@open-pencil/core/io'
+import { SceneGraph, type VectorNetwork } from '@open-pencil/scene-graph'
+
+import { expectDefined } from '../helpers/assert'
+
+const ck = await initCanvasKit()
+const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1)))
+afterAll(() => renderer.destroy())
+
+const zero = { x: 0, y: 0 }
+
+/** The alpha at a point of a 100px frame holding an unfilled L-shaped path, stroked 20 wide. */
+function alphaAt(x: number, y: number, join: 'MITER' | 'BEVEL'): number {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const frame = graph.createNode('FRAME', page, {
+ width: 100,
+ height: 100,
+ fills: [],
+ clipsContent: false
+ })
+ // Right along the top, then down: (20, 20) → (80, 20) → (80, 80) in the frame.
+ const network: VectorNetwork = {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 60, y: 0 },
+ { x: 60, y: 60 }
+ ],
+ segments: [
+ { start: 0, end: 1, tangentStart: zero, tangentEnd: zero },
+ { start: 1, end: 2, tangentStart: zero, tangentEnd: zero }
+ ],
+ regions: []
+ }
+ graph.createNode('VECTOR', frame.id, {
+ x: 20,
+ y: 20,
+ width: 60,
+ height: 60,
+ vectorNetwork: network,
+ fills: [],
+ strokes: [
+ {
+ type: 'SOLID',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ weight: 20,
+ align: 'CENTER',
+ cap: 'NONE',
+ join
+ }
+ ],
+ strokeWeight: 20,
+ strokeAlign: 'CENTER',
+ strokeJoin: join,
+ strokeCap: 'NONE'
+ })
+ const png = expectDefined(
+ renderNodesToImage(ck, renderer, graph, page, [frame.id], {
+ scale: 1,
+ format: 'PNG',
+ trimTransparent: false
+ })
+ )
+ const image = expectDefined(ck.MakeImageFromEncoded(png))
+ try {
+ const offset = (image.width() - 100) / 2
+ const pixels = expectDefined(
+ image.readPixels(0, 0, {
+ width: image.width(),
+ height: image.height(),
+ alphaType: ck.AlphaType.Unpremul,
+ colorType: ck.ColorType.RGBA_8888,
+ colorSpace: ck.ColorSpace.SRGB
+ })
+ )
+ return pixels[((y + offset) * image.width() + x + offset) * 4 + 3]
+ } finally {
+ image.delete()
+ }
+}
+
+describe('stroking a vector path', () => {
+ test('a corner takes the stroke’s join, filling the outer corner with a miter', () => {
+ // Outside the corner at (80, 20), where neither leg's own stroke reaches.
+ expect(alphaAt(87, 13, 'MITER')).toBe(255)
+ })
+
+ test('a bevel cuts that corner off', () => {
+ expect(alphaAt(88, 12, 'BEVEL')).toBe(0)
+ // Inside the bevel, near the corner.
+ expect(alphaAt(84, 16, 'BEVEL')).toBe(255)
+ })
+})
diff --git a/packages/core/tests/vector/stroke-runs.test.ts b/packages/core/tests/vector/stroke-runs.test.ts
new file mode 100644
index 000000000..cf9c53f85
--- /dev/null
+++ b/packages/core/tests/vector/stroke-runs.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, test } from 'bun:test'
+
+import type { VectorSegment, VectorVertex } from '@open-pencil/scene-graph'
+
+import { addStrokeRunToPath, strokeRuns, type PathSink } from '#core/vector/path-helpers'
+
+const zero = { x: 0, y: 0 }
+
+function line(start: number, end: number): VectorSegment {
+ return { start, end, tangentStart: zero, tangentEnd: zero }
+}
+
+/** Records path commands as strings. */
+function recorder(): PathSink & { commands: string[] } {
+ const commands: string[] = []
+ return {
+ commands,
+ moveTo: (x, y) => commands.push(`M${x},${y}`),
+ lineTo: (x, y) => commands.push(`L${x},${y}`),
+ cubicTo: (_x1, _y1, _x2, _y2, x, y) => commands.push(`C${x},${y}`),
+ close: () => commands.push('Z')
+ }
+}
+
+function draw(segments: VectorSegment[], vertices: VectorVertex[]) {
+ return strokeRuns(segments).map((run) => {
+ const path = recorder()
+ addStrokeRunToPath(path, run, segments, vertices)
+ return path.commands.join(' ')
+ })
+}
+
+describe('stroke runs', () => {
+ test('an open polyline strokes as one contour, so its corners join', () => {
+ const vertices = [
+ { x: 0, y: 0 },
+ { x: 10, y: 0 },
+ { x: 10, y: 10 }
+ ]
+ expect(draw([line(0, 1), line(1, 2)], vertices)).toEqual(['M0,0 L10,0 L10,10'])
+ })
+
+ test('segments stored out of order and against the drawing direction still chain', () => {
+ const vertices = [
+ { x: 0, y: 0 },
+ { x: 10, y: 0 },
+ { x: 10, y: 10 },
+ { x: 0, y: 10 }
+ ]
+ // The middle segment comes first and runs backwards; the run starts at an open end.
+ const runs = draw([line(2, 1), line(0, 1), line(2, 3)], vertices)
+ expect(runs).toHaveLength(1)
+ expect(['M0,0 L10,0 L10,10 L0,10', 'M0,10 L10,10 L10,0 L0,0']).toContain(runs[0])
+ })
+
+ test('a loop closes, so its first corner joins too', () => {
+ const vertices = [
+ { x: 0, y: 0 },
+ { x: 10, y: 0 },
+ { x: 10, y: 10 }
+ ]
+ expect(draw([line(0, 1), line(1, 2), line(2, 0)], vertices)).toEqual([
+ 'M0,0 L10,0 L10,10 L0,0 Z'
+ ])
+ })
+
+ test('a junction of three segments ends the runs that meet there', () => {
+ const vertices = [
+ { x: 0, y: 0 },
+ { x: -10, y: 0 },
+ { x: 10, y: 0 },
+ { x: 0, y: 10 }
+ ]
+ const runs = strokeRuns([line(0, 1), line(0, 2), line(0, 3)])
+ expect(runs.map((run) => run.segments)).toEqual([[0], [1], [2]])
+ expect(runs.every((run) => !run.closed)).toBe(true)
+ expect(draw([line(0, 1), line(0, 2), line(0, 3)], vertices)).toHaveLength(3)
+ })
+
+ test('a loop through a junction closes whichever of its segments is stored first', () => {
+ // A square with a tail from its top-left corner, the junction.
+ const square = [line(0, 1), line(1, 2), line(2, 3), line(3, 0)]
+ const tail = line(0, 4)
+ for (const segments of [
+ [...square, tail],
+ [square[1], square[2], square[3], square[0], tail]
+ ]) {
+ const loop = strokeRuns(segments).find((run) => run.segments.length === 4)
+ expect(loop?.closed).toBe(true)
+ }
+ })
+
+ test('a curve drawn backwards swaps its handles', () => {
+ const vertices = [
+ { x: 0, y: 0 },
+ { x: 10, y: 0 },
+ { x: 20, y: 0 }
+ ]
+ const curve = { start: 2, end: 1, tangentStart: { x: 0, y: 5 }, tangentEnd: { x: 0, y: -5 } }
+ const path = recorder()
+ const cubic: number[][] = []
+ path.cubicTo = (...args) => cubic.push(args)
+ for (const run of strokeRuns([line(0, 1), curve]))
+ addStrokeRunToPath(path, run, [line(0, 1), curve], vertices)
+ // Drawn from vertex 1 to 2: the first handle hangs off vertex 1 by tangentEnd.
+ expect(cubic).toEqual([[10, -5, 20, 5, 20, 0]])
+ })
+})
diff --git a/packages/scene-graph/src/geometry.ts b/packages/scene-graph/src/geometry.ts
index 9b21d991c..28d0372ee 100644
--- a/packages/scene-graph/src/geometry.ts
+++ b/packages/scene-graph/src/geometry.ts
@@ -1,5 +1,5 @@
import { arrowCapOverflow } from './arrow-caps'
-import type { Effect, Stroke, StrokeCap, VectorNetwork } from './index'
+import type { Effect, Stroke, StrokeCap, StrokeJoin, VectorNetwork } from './index'
import type { Rect, Vector } from './primitives'
export function degToRad(degrees: number): number {
@@ -138,10 +138,17 @@ export function polygonVertices(node: {
})
}
+/** A layer's stroke join and miter limit, for the tips mitered path corners reach. */
+export interface StrokeCorners {
+ strokeJoin?: StrokeJoin
+ strokeMiterLimit?: number
+}
+
export function strokeOverflow(
strokes?: Stroke[],
fallbackCap?: StrokeCap,
- network?: VectorNetwork | null
+ network?: VectorNetwork | null,
+ corners?: StrokeCorners
): number {
let overflow = 0
for (const stroke of strokes ?? []) {
@@ -149,11 +156,52 @@ export function strokeOverflow(
let extra = 0
if (stroke.align === 'OUTSIDE') extra = stroke.weight
else if (stroke.align === 'CENTER') extra = stroke.weight / 2
- overflow = Math.max(overflow, extra)
+ const miter = network
+ ? miterRatio(network, stroke.join ?? corners?.strokeJoin, corners?.strokeMiterLimit)
+ : 1
+ overflow = Math.max(overflow, extra * miter)
}
return Math.max(overflow, arrowCapOverflow(strokes, fallbackCap, network))
}
+/** The direction a segment leaves `vertex` in, along its handle when it has one. */
+function leaving(network: VectorNetwork, index: number, vertex: number): Vector {
+ const segment = network.segments[index]
+ const atStart = segment.start === vertex
+ const handle = atStart ? segment.tangentStart : segment.tangentEnd
+ if (handle.x !== 0 || handle.y !== 0) return handle
+ const from = network.vertices[vertex]
+ const to = network.vertices[atStart ? segment.end : segment.start]
+ return { x: to.x - from.x, y: to.y - from.y }
+}
+
+/**
+ * How far past half the stroke the sharpest mitered corner reaches, as a multiple: a corner of
+ * angle θ mitres out to 1/sin(θ/2), unless that passes the miter limit and it bevels instead.
+ * Corners are the vertices exactly two segments meet at, as the stroke joins them.
+ */
+function miterRatio(network: VectorNetwork, join: StrokeJoin | undefined, limit = 4): number {
+ const meeting = new Map<number, number[]>()
+ for (const [index, segment] of network.segments.entries()) {
+ for (const vertex of new Set([segment.start, segment.end])) {
+ meeting.set(vertex, [...(meeting.get(vertex) ?? []), index])
+ }
+ }
+ let ratio = 1
+ for (const [vertex, indices] of meeting) {
+ if (indices.length !== 2) continue
+ if ((network.vertices[vertex].strokeJoin ?? join ?? 'MITER') !== 'MITER') continue
+ const a = leaving(network, indices[0], vertex)
+ const b = leaving(network, indices[1], vertex)
+ const lengths = Math.hypot(a.x, a.y) * Math.hypot(b.x, b.y)
+ if (lengths === 0) continue
+ const angle = Math.acos(Math.max(-1, Math.min(1, (a.x * b.x + a.y * b.y) / lengths)))
+ const miter = 1 / Math.sin(angle / 2)
+ if (miter <= limit) ratio = Math.max(ratio, miter)
+ }
+ return ratio
+}
+
export function effectOverflow(effects?: Effect[]) {
let left = 0
let right = 0
@@ -192,16 +240,18 @@ export function computeAbsoluteBounds(
}
export function computeVisualBounds(
- nodes: Iterable<{
- id: string
- width: number
- height: number
- rotation?: number
- strokes?: Stroke[]
- strokeCap?: StrokeCap
- vectorNetwork?: VectorNetwork | null
- effects?: Effect[]
- }>,
+ nodes: Iterable<
+ {
+ id: string
+ width: number
+ height: number
+ rotation?: number
+ strokes?: Stroke[]
+ strokeCap?: StrokeCap
+ vectorNetwork?: VectorNetwork | null
+ effects?: Effect[]
+ } & StrokeCorners
+ >,
getAbsolutePosition: (id: string) => Vector
): Rect {
const bounds = createBoundsAccumulator()
@@ -209,7 +259,7 @@ export function computeVisualBounds(
for (const n of nodes) {
const abs = getAbsolutePosition(n.id)
const bbox = rotatedBBox(abs.x, abs.y, n.width, n.height, n.rotation ?? 0)
- const stroke = strokeOverflow(n.strokes, n.strokeCap, n.vectorNetwork)
+ const stroke = strokeOverflow(n.strokes, n.strokeCap, n.vectorNetwork, n)
const effects = effectOverflow(n.effects)
includePoint(bounds, bbox.left - stroke - effects.left, bbox.top - stroke - effects.top)
includePoint(bounds, bbox.right + stroke + effects.right, bbox.bottom + stroke + effects.bottom)
diff --git a/tests/e2e/canvas/stroke-geometry-visual.spec.ts b/tests/e2e/canvas/stroke-geometry-visual.spec.ts
index 16a8a13b0..8efdb6a6c 100644
--- a/tests/e2e/canvas/stroke-geometry-visual.spec.ts
+++ b/tests/e2e/canvas/stroke-geometry-visual.spec.ts
@@ -80,3 +80,105 @@ test('stroke caps joins and miter limits', async () => {
const buffer = await editor.canvas.screenshotCanvasRegion()
expect(buffer).toMatchSnapshot('stroke-caps-joins-miter-limits.png')
})
+
+test('vector path corners take the stroke join', async () => {
+ await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const pageId = store.state.currentPageId
+ const zero = { x: 0, y: 0 }
+ const line = (start: number, end: number) => ({
+ start,
+ end,
+ tangentStart: zero,
+ tangentEnd: zero
+ })
+ const stroke = (join: 'MITER' | 'BEVEL' | 'ROUND') => [
+ {
+ type: 'SOLID' as const,
+ color: { r: 0.23, g: 0.51, b: 0.96, a: 1 },
+ weight: 16,
+ visible: true,
+ opacity: 1,
+ align: 'CENTER' as const,
+ join
+ }
+ ]
+ // An open zigzag, unfilled, once per join.
+ const joins = ['MITER', 'BEVEL', 'ROUND'] as const
+ for (const [index, join] of joins.entries()) {
+ store.graph.createNode('VECTOR', pageId, {
+ name: `${join} polyline join visual`,
+ x: 72 + index * 190,
+ y: 80,
+ width: 140,
+ height: 90,
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 90 },
+ { x: 45, y: 0 },
+ { x: 90, y: 90 },
+ { x: 140, y: 20 }
+ ],
+ segments: [line(0, 1), line(1, 2), line(2, 3)],
+ regions: []
+ },
+ strokeJoin: join,
+ strokeMiterLimit: 4,
+ fills: [],
+ strokes: stroke(join)
+ })
+ }
+ // A closed loop with no region: its first corner joins like the others.
+ store.graph.createNode('VECTOR', pageId, {
+ name: 'closed loop join visual',
+ x: 120,
+ y: 230,
+ width: 120,
+ height: 100,
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 120, y: 30 },
+ { x: 40, y: 100 }
+ ],
+ segments: [line(0, 1), line(1, 2), line(2, 0)],
+ regions: []
+ },
+ strokeJoin: 'MITER',
+ strokeMiterLimit: 4,
+ fills: [],
+ strokes: stroke('MITER')
+ })
+ // A loop with a tail from its first corner, stored starting from the next corner.
+ store.graph.createNode('VECTOR', pageId, {
+ name: 'loop with tail join visual',
+ x: 340,
+ y: 230,
+ width: 180,
+ height: 100,
+ vectorNetwork: {
+ vertices: [
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 100, y: 100 },
+ { x: 0, y: 100 },
+ { x: 180, y: 50 }
+ ],
+ segments: [line(1, 2), line(2, 3), line(3, 0), line(0, 1), line(0, 4)],
+ regions: []
+ },
+ strokeJoin: 'MITER',
+ strokeMiterLimit: 4,
+ fills: [],
+ strokes: stroke('MITER')
+ })
+
+ store.clearSelection()
+ store.requestRender()
+ })
+ await editor.canvas.waitForRender()
+ editor.canvas.assertNoErrors()
+ const buffer = await editor.canvas.screenshotCanvasRegion()
+ expect(buffer).toMatchSnapshot('vector-path-joins.png')
+})
diff --git a/tests/e2e/canvas/stroke-geometry-visual.spec.ts-snapshots/vector-path-joins-openpencil-darwin.png b/tests/e2e/canvas/stroke-geometry-visual.spec.ts-snapshots/vector-path-joins-openpencil-darwin.png
new file mode 100644
index 000000000..d2655dcfd
Binary files /dev/null and b/tests/e2e/canvas/stroke-geometry-visual.spec.ts-snapshots/vector-path-joins-openpencil-darwin.png differ
diff --git a/tests/engine/geometry/visual-bounds.test.ts b/tests/engine/geometry/visual-bounds.test.ts
index ed7a2de1a..7a9d660f4 100644
--- a/tests/engine/geometry/visual-bounds.test.ts
+++ b/tests/engine/geometry/visual-bounds.test.ts
@@ -4,7 +4,8 @@ import type { Vector } from '@open-pencil/scene-graph'
import type { VisualBoundsNode } from '@open-pencil/scene-graph/geometry'
import {
computeDescendantVisualBounds,
- computeVisualBounds
+ computeVisualBounds,
+ strokeOverflow
} from '@open-pencil/scene-graph/geometry'
function commandsBlobFromPoints(points: Vector[]): Uint8Array {
@@ -534,3 +535,44 @@ describe('computeVisualBounds', () => {
expect(multiEffect.height).toBe(noEffects.height + 5 + 5) // 60 + 10 = 70
})
})
+
+describe('strokeOverflow at mitered corners', () => {
+ const stroke = {
+ type: 'SOLID' as const,
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ weight: 10,
+ opacity: 1,
+ visible: true,
+ align: 'CENTER' as const
+ }
+ const zero = { x: 0, y: 0 }
+ /** An open chevron whose apex is a 40° corner. */
+ const half = Math.tan((20 * Math.PI) / 180) * 100
+ const chevron = {
+ vertices: [
+ { x: -half, y: 100 },
+ { x: 0, y: 0 },
+ { x: half, y: 100 }
+ ],
+ segments: [
+ { start: 0, end: 1, tangentStart: zero, tangentEnd: zero },
+ { start: 1, end: 2, tangentStart: zero, tangentEnd: zero }
+ ],
+ regions: []
+ }
+
+ test('reaches the miter tip, as Figma’s render bounds do', () => {
+ // Half the weight over sin(20°): 14.6.
+ expect(strokeOverflow([stroke], 'NONE', chevron, { strokeJoin: 'MITER' })).toBeCloseTo(
+ 5 / Math.sin((20 * Math.PI) / 180),
+ 6
+ )
+ })
+
+ test('stays at half the weight for round joins and past the miter limit', () => {
+ expect(strokeOverflow([stroke], 'NONE', chevron, { strokeJoin: 'ROUND' })).toBe(5)
+ expect(
+ strokeOverflow([stroke], 'NONE', chevron, { strokeJoin: 'MITER', strokeMiterLimit: 2 })
+ ).toBe(5)
+ })
+})