Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: prevent division by zero in bezier #785

Merged
merged 1 commit into from
Aug 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/bezier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export class Bezier {
const dxm = m1.x - m2.x;
const dym = m1.y - m2.y;

const k = l2 / (l1 + l2);
const k = l1 + l2 == 0 ? 0 : l2 / (l1 + l2);
const cm = { x: m2.x + dxm * k, y: m2.y + dym * k };

const tx = s2.x - cm.x;
Expand Down
19 changes: 19 additions & 0 deletions tests/bezier.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,25 @@ describe('.fromPoints', () => {
expect(curve.endWidth).toBe(2);
});
});

it('returns a new Bézier when points are equal and division by zero may occur', () => {
const now = Date.now();

freezeTimeAt(now, () => {
const p1 = new Point(54.4, 10.9, 0.5);
const p2 = new Point(54.4, 10.9, 0.5);
const p3 = new Point(54.4, 10.9, 0.5);
const p4 = new Point(54.4, 10.9, 0.5);
const curve = Bezier.fromPoints([p1, p2, p3, p4], { start: 1, end: 1 });

expect(curve.startPoint).toEqual(p2);
expect(curve.control1).toEqual(new Point(54.4, 10.9));
expect(curve.control2).toEqual(new Point(54.4, 10.9));
expect(curve.endPoint).toBe(p3);
expect(curve.startWidth).toBe(1);
expect(curve.endWidth).toBe(1);
});
});
});

describe('#length', () => {
Expand Down
Loading