Skip to content

Commit bfc1287

Browse files
bernhardfritzmgechev
authored andcommitted
add bezier curve algorithm
1 parent 396d83c commit bfc1287

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

src/graphics/bezier.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
(function (exports) {
2+
'use strict';
3+
4+
function linearBezier(p0, p1, t) {
5+
return p0 + t * (p1 - p0);
6+
}
7+
8+
function quadraticBezier(p0, p1, p2, t) {
9+
return linearBezier(linearBezier(p0, p1, t), linearBezier(p1, p2, t), t);
10+
}
11+
12+
function cubicBezier(p0, p1, p2, p3, t) {
13+
return linearBezier(quadraticBezier(p0, p1, p2, t), quadraticBezier(p1, p2, p3, t), t);
14+
}
15+
16+
exports.linearBezier = linearBezier;
17+
exports.quadraticBezier = quadraticBezier;
18+
exports.cubicBezier = cubicBezier;
19+
})(typeof exports === 'undefined' ? window : exports);

test/graphics/bezier.spec.js

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
var bezier = require('../../src/graphics/bezier');
2+
var linearBezier = bezier.linearBezier;
3+
var quadraticBezier = bezier.quadraticBezier;
4+
var cubicBezier = bezier.cubicBezier;
5+
6+
// see https://www.geogebra.org/m/ek7RHvuc for graphical representation of test values
7+
8+
describe('linearBezier', function () {
9+
'use strict';
10+
11+
it('should return 0.5 for p0=0 p1=1 t=0.5', function () {
12+
expect(linearBezier(0, 1, 0.5)).toEqual(0.5);
13+
});
14+
15+
it('should return -2.8 for p0=-4.67 p1=-0.7 t=0.47', function () {
16+
expect(linearBezier(-4.67, -0.7, 0.47)).toBeCloseTo(-2.8, 1);
17+
});
18+
19+
it('should return 2.67 for p0=-0.6 p1=6.33 t=0.47', function () {
20+
expect(linearBezier(-0.6, 6.33, 0.47)).toBeCloseTo(2.67, 1);
21+
});
22+
});
23+
24+
describe('quadraticBezier', function () {
25+
'use strict';
26+
27+
it('should return 1 for p0=0 p1=1 p2=2 t=0.5', function () {
28+
expect(quadraticBezier(0, 1, 2, 0.5)).toEqual(1);
29+
});
30+
31+
it('should return 7.15 for p0=2.33 p1=8.23 p2=10.77 t=0.47', function () {
32+
expect(quadraticBezier(2.33, 8.23, 10.77, 0.47)).toBeCloseTo(7.15, 1);
33+
});
34+
35+
it('should return 6.84 for p0=4.67 p1=8.93 p2=4.9 t=0.47', function () {
36+
expect(quadraticBezier(4.67, 8.93, 4.9, 0.47)).toBeCloseTo(6.84, 1);
37+
});
38+
});
39+
40+
describe('cubicBezier', function () {
41+
'use strict';
42+
43+
it('should return 1.5 for p0=0 p1=1 p2=2 p3=3 t=0.5', function () {
44+
expect(cubicBezier(0, 1, 2, 3, 0.5)).toEqual(1.5);
45+
});
46+
47+
it('should return 9.78 for p0=2.4 p1=1.33 p2=19.87 p3=18.13 t=0.47', function () {
48+
expect(cubicBezier(2.4, 1.33, 19.87, 18.13, 0.47)).toBeCloseTo(9.78, 1);
49+
});
50+
51+
it('should return -4.87 for p0=-7.03 p1=-1.4 p2=-10.63 p3=4.5 t=0.47', function () {
52+
expect(cubicBezier(-7.03, -1.4, -10.63, 4.5, 0.47)).toBeCloseTo(-4.87, 1);
53+
});
54+
});

0 commit comments

Comments
 (0)