source: node_modules/d3-shape/src/curve/natural.js@ e4c61dd

Last change on this file since e4c61dd was e4c61dd, checked in by istevanoska <ilinastevanoska@…>, 6 months ago

Prototype 1.1

  • Property mode set to 100644
File size: 1.7 KB
Line 
1function Natural(context) {
2 this._context = context;
3}
4
5Natural.prototype = {
6 areaStart: function() {
7 this._line = 0;
8 },
9 areaEnd: function() {
10 this._line = NaN;
11 },
12 lineStart: function() {
13 this._x = [];
14 this._y = [];
15 },
16 lineEnd: function() {
17 var x = this._x,
18 y = this._y,
19 n = x.length;
20
21 if (n) {
22 this._line ? this._context.lineTo(x[0], y[0]) : this._context.moveTo(x[0], y[0]);
23 if (n === 2) {
24 this._context.lineTo(x[1], y[1]);
25 } else {
26 var px = controlPoints(x),
27 py = controlPoints(y);
28 for (var i0 = 0, i1 = 1; i1 < n; ++i0, ++i1) {
29 this._context.bezierCurveTo(px[0][i0], py[0][i0], px[1][i0], py[1][i0], x[i1], y[i1]);
30 }
31 }
32 }
33
34 if (this._line || (this._line !== 0 && n === 1)) this._context.closePath();
35 this._line = 1 - this._line;
36 this._x = this._y = null;
37 },
38 point: function(x, y) {
39 this._x.push(+x);
40 this._y.push(+y);
41 }
42};
43
44// See https://www.particleincell.com/2012/bezier-splines/ for derivation.
45function controlPoints(x) {
46 var i,
47 n = x.length - 1,
48 m,
49 a = new Array(n),
50 b = new Array(n),
51 r = new Array(n);
52 a[0] = 0, b[0] = 2, r[0] = x[0] + 2 * x[1];
53 for (i = 1; i < n - 1; ++i) a[i] = 1, b[i] = 4, r[i] = 4 * x[i] + 2 * x[i + 1];
54 a[n - 1] = 2, b[n - 1] = 7, r[n - 1] = 8 * x[n - 1] + x[n];
55 for (i = 1; i < n; ++i) m = a[i] / b[i - 1], b[i] -= m, r[i] -= m * r[i - 1];
56 a[n - 1] = r[n - 1] / b[n - 1];
57 for (i = n - 2; i >= 0; --i) a[i] = (r[i] - a[i + 1]) / b[i];
58 b[n - 1] = (x[n] + a[n - 1]) / 2;
59 for (i = 0; i < n - 1; ++i) b[i] = 2 * x[i + 1] - a[i + 1];
60 return [a, b];
61}
62
63export default function(context) {
64 return new Natural(context);
65}
Note: See TracBrowser for help on using the repository browser.