diff --git a/src/toPath.js b/src/toPath.js index 8096550..da642e8 100644 --- a/src/toPath.js +++ b/src/toPath.js @@ -3,17 +3,18 @@ import toPoints from './toPoints' const pointsToD = p => { let d = '' let i = 0 - let firstPointInCurrentLine + let firstPoint for (let point of p) { - const isFirstPoint = i === 0 - const isLastPoint = i === p.length - 1 - const prevPoint = isFirstPoint ? null : p[ i - 1 ] const { curve = false, moveTo, x, y } = point + const isFirstPoint = i === 0 || moveTo + const isLastPoint = i === p.length - 1 || p[ i + 1 ].moveTo + const prevPoint = i === 0 ? null : p[ i - 1 ] + + if (isFirstPoint) { + firstPoint = point - if (moveTo || isFirstPoint) { if (!isLastPoint) { - firstPointInCurrentLine = point d += `M${x},${y}` } } else if (curve) { @@ -32,10 +33,10 @@ const pointsToD = p => { break } - if (isLastPoint && x === firstPointInCurrentLine.x && y === firstPointInCurrentLine.y) { + if (isLastPoint && x === firstPoint.x && y === firstPoint.y) { d += 'Z' } - } else if (isLastPoint && x === firstPointInCurrentLine.x && y === firstPointInCurrentLine.y) { + } else if (isLastPoint && x === firstPoint.x && y === firstPoint.y) { d += 'Z' } else if (x !== prevPoint.x && y !== prevPoint.y) { d += `L${x},${y}` diff --git a/test/toPath.js b/test/toPath.js index 4059542..4b74971 100644 --- a/test/toPath.js +++ b/test/toPath.js @@ -324,3 +324,22 @@ test('does not close path when last point does not match corresponding moveTo po expect(path).toEqual(expectedPath) }) + +test('closes any line where first and last points match', () => { + const points = [ + { x: 10, y: 10, moveTo: true }, + { x: 10, y: 100 }, + { x: 100, y: 10, moveTo: true }, + { x: 200, y: 100 }, + { x: 100, y: 100 }, + { x: 100, y: 10 }, + { x: 200, y: 10, moveTo: true }, + { x: 10, y: 10 } + ] + + const expectedPath = 'M10,10V100M100,10L200,100H100ZM200,10H10' + + const path = toPath(points) + + expect(path).toEqual(expectedPath) +})