-
Notifications
You must be signed in to change notification settings - Fork 145
/
Copy pathsvgpath.js
1523 lines (1191 loc) · 36.2 KB
/
svgpath.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require=(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
// Convert an arc to a sequence of cubic bézier curves
//
'use strict';
var TAU = Math.PI * 2;
/* eslint-disable space-infix-ops */
// Calculate an angle between two unit vectors
//
// Since we measure angle between radii of circular arcs,
// we can use simplified math (without length normalization)
//
function unit_vector_angle(ux, uy, vx, vy) {
var sign = (ux * vy - uy * vx < 0) ? -1 : 1;
var dot = ux * vx + uy * vy;
// Add this to work with arbitrary vectors:
// dot /= Math.sqrt(ux * ux + uy * uy) * Math.sqrt(vx * vx + vy * vy);
// rounding errors, e.g. -1.0000000000000002 can screw up this
if (dot > 1.0) { dot = 1.0; }
if (dot < -1.0) { dot = -1.0; }
return sign * Math.acos(dot);
}
// Convert from endpoint to center parameterization,
// see http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
//
// Return [cx, cy, theta1, delta_theta]
//
function get_arc_center(x1, y1, x2, y2, fa, fs, rx, ry, sin_phi, cos_phi) {
// Step 1.
//
// Moving an ellipse so origin will be the middlepoint between our two
// points. After that, rotate it to line up ellipse axes with coordinate
// axes.
//
var x1p = cos_phi*(x1-x2)/2 + sin_phi*(y1-y2)/2;
var y1p = -sin_phi*(x1-x2)/2 + cos_phi*(y1-y2)/2;
var rx_sq = rx * rx;
var ry_sq = ry * ry;
var x1p_sq = x1p * x1p;
var y1p_sq = y1p * y1p;
// Step 2.
//
// Compute coordinates of the centre of this ellipse (cx', cy')
// in the new coordinate system.
//
var radicant = (rx_sq * ry_sq) - (rx_sq * y1p_sq) - (ry_sq * x1p_sq);
if (radicant < 0) {
// due to rounding errors it might be e.g. -1.3877787807814457e-17
radicant = 0;
}
radicant /= (rx_sq * y1p_sq) + (ry_sq * x1p_sq);
radicant = Math.sqrt(radicant) * (fa === fs ? -1 : 1);
var cxp = radicant * rx/ry * y1p;
var cyp = radicant * -ry/rx * x1p;
// Step 3.
//
// Transform back to get centre coordinates (cx, cy) in the original
// coordinate system.
//
var cx = cos_phi*cxp - sin_phi*cyp + (x1+x2)/2;
var cy = sin_phi*cxp + cos_phi*cyp + (y1+y2)/2;
// Step 4.
//
// Compute angles (theta1, delta_theta).
//
var v1x = (x1p - cxp) / rx;
var v1y = (y1p - cyp) / ry;
var v2x = (-x1p - cxp) / rx;
var v2y = (-y1p - cyp) / ry;
var theta1 = unit_vector_angle(1, 0, v1x, v1y);
var delta_theta = unit_vector_angle(v1x, v1y, v2x, v2y);
if (fs === 0 && delta_theta > 0) {
delta_theta -= TAU;
}
if (fs === 1 && delta_theta < 0) {
delta_theta += TAU;
}
return [ cx, cy, theta1, delta_theta ];
}
//
// Approximate one unit arc segment with bézier curves,
// see http://math.stackexchange.com/questions/873224
//
function approximate_unit_arc(theta1, delta_theta) {
var alpha = 4/3 * Math.tan(delta_theta/4);
var x1 = Math.cos(theta1);
var y1 = Math.sin(theta1);
var x2 = Math.cos(theta1 + delta_theta);
var y2 = Math.sin(theta1 + delta_theta);
return [ x1, y1, x1 - y1*alpha, y1 + x1*alpha, x2 + y2*alpha, y2 - x2*alpha, x2, y2 ];
}
module.exports = function a2c(x1, y1, x2, y2, fa, fs, rx, ry, phi) {
var sin_phi = Math.sin(phi * TAU / 360);
var cos_phi = Math.cos(phi * TAU / 360);
// Make sure radii are valid
//
var x1p = cos_phi*(x1-x2)/2 + sin_phi*(y1-y2)/2;
var y1p = -sin_phi*(x1-x2)/2 + cos_phi*(y1-y2)/2;
if (x1p === 0 && y1p === 0) {
// we're asked to draw line to itself
return [];
}
if (rx === 0 || ry === 0) {
// one of the radii is zero
return [];
}
// Compensate out-of-range radii
//
rx = Math.abs(rx);
ry = Math.abs(ry);
var lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
if (lambda > 1) {
rx *= Math.sqrt(lambda);
ry *= Math.sqrt(lambda);
}
// Get center parameters (cx, cy, theta1, delta_theta)
//
var cc = get_arc_center(x1, y1, x2, y2, fa, fs, rx, ry, sin_phi, cos_phi);
var result = [];
var theta1 = cc[2];
var delta_theta = cc[3];
// Split an arc to multiple segments, so each segment
// will be less than τ/4 (= 90°)
//
var segments = Math.max(Math.ceil(Math.abs(delta_theta) / (TAU / 4)), 1);
delta_theta /= segments;
for (var i = 0; i < segments; i++) {
result.push(approximate_unit_arc(theta1, delta_theta));
theta1 += delta_theta;
}
// We have a bezier approximation of a unit circle,
// now need to transform back to the original ellipse
//
return result.map(function (curve) {
for (var i = 0; i < curve.length; i += 2) {
var x = curve[i + 0];
var y = curve[i + 1];
// scale
x *= rx;
y *= ry;
// rotate
var xp = cos_phi*x - sin_phi*y;
var yp = sin_phi*x + cos_phi*y;
// translate
curve[i + 0] = xp + cc[0];
curve[i + 1] = yp + cc[1];
}
return curve;
});
};
},{}],2:[function(require,module,exports){
'use strict';
/* eslint-disable space-infix-ops */
// The precision used to consider an ellipse as a circle
//
var epsilon = 0.0000000001;
// To convert degree in radians
//
var torad = Math.PI / 180;
// Class constructor :
// an ellipse centred at 0 with radii rx,ry and x - axis - angle ax.
//
function Ellipse(rx, ry, ax) {
if (!(this instanceof Ellipse)) { return new Ellipse(rx, ry, ax); }
this.rx = rx;
this.ry = ry;
this.ax = ax;
}
// Apply a linear transform m to the ellipse
// m is an array representing a matrix :
// - -
// | m[0] m[2] |
// | m[1] m[3] |
// - -
//
Ellipse.prototype.transform = function (m) {
// We consider the current ellipse as image of the unit circle
// by first scale(rx,ry) and then rotate(ax) ...
// So we apply ma = m x rotate(ax) x scale(rx,ry) to the unit circle.
var c = Math.cos(this.ax * torad), s = Math.sin(this.ax * torad);
var ma = [
this.rx * (m[0]*c + m[2]*s),
this.rx * (m[1]*c + m[3]*s),
this.ry * (-m[0]*s + m[2]*c),
this.ry * (-m[1]*s + m[3]*c)
];
// ma * transpose(ma) = [ J L ]
// [ L K ]
// L is calculated later (if the image is not a circle)
var J = ma[0]*ma[0] + ma[2]*ma[2],
K = ma[1]*ma[1] + ma[3]*ma[3];
// the discriminant of the characteristic polynomial of ma * transpose(ma)
var D = ((ma[0]-ma[3])*(ma[0]-ma[3]) + (ma[2]+ma[1])*(ma[2]+ma[1])) *
((ma[0]+ma[3])*(ma[0]+ma[3]) + (ma[2]-ma[1])*(ma[2]-ma[1]));
// the "mean eigenvalue"
var JK = (J + K) / 2;
// check if the image is (almost) a circle
if (D < epsilon * JK) {
// if it is
this.rx = this.ry = Math.sqrt(JK);
this.ax = 0;
return this;
}
// if it is not a circle
var L = ma[0]*ma[1] + ma[2]*ma[3];
D = Math.sqrt(D);
// {l1,l2} = the two eigen values of ma * transpose(ma)
var l1 = JK + D/2,
l2 = JK - D/2;
// the x - axis - rotation angle is the argument of the l1 - eigenvector
/*eslint-disable indent*/
this.ax = (Math.abs(L) < epsilon && Math.abs(l1 - K) < epsilon) ?
90
:
Math.atan(Math.abs(L) > Math.abs(l1 - K) ?
(l1 - J) / L
:
L / (l1 - K)
) * 180 / Math.PI;
/*eslint-enable indent*/
// if ax > 0 => rx = sqrt(l1), ry = sqrt(l2), else exchange axes and ax += 90
if (this.ax >= 0) {
// if ax in [0,90]
this.rx = Math.sqrt(l1);
this.ry = Math.sqrt(l2);
} else {
// if ax in ]-90,0[ => exchange axes
this.ax += 90;
this.rx = Math.sqrt(l2);
this.ry = Math.sqrt(l1);
}
return this;
};
// Check if the ellipse is (almost) degenerate, i.e. rx = 0 or ry = 0
//
Ellipse.prototype.isDegenerate = function () {
return (this.rx < epsilon * this.ry || this.ry < epsilon * this.rx);
};
module.exports = Ellipse;
},{}],3:[function(require,module,exports){
'use strict';
// combine 2 matrixes
// m1, m2 - [a, b, c, d, e, g]
//
function combine(m1, m2) {
return [
m1[0] * m2[0] + m1[2] * m2[1],
m1[1] * m2[0] + m1[3] * m2[1],
m1[0] * m2[2] + m1[2] * m2[3],
m1[1] * m2[2] + m1[3] * m2[3],
m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
];
}
function Matrix() {
if (!(this instanceof Matrix)) { return new Matrix(); }
this.queue = []; // list of matrixes to apply
this.cache = null; // combined matrix cache
}
Matrix.prototype.matrix = function (m) {
if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 && m[4] === 0 && m[5] === 0) {
return this;
}
this.cache = null;
this.queue.push(m);
return this;
};
Matrix.prototype.translate = function (tx, ty) {
if (tx !== 0 || ty !== 0) {
this.cache = null;
this.queue.push([ 1, 0, 0, 1, tx, ty ]);
}
return this;
};
Matrix.prototype.scale = function (sx, sy) {
if (sx !== 1 || sy !== 1) {
this.cache = null;
this.queue.push([ sx, 0, 0, sy, 0, 0 ]);
}
return this;
};
Matrix.prototype.rotate = function (angle, rx, ry) {
var rad, cos, sin;
if (angle !== 0) {
this.translate(rx, ry);
rad = angle * Math.PI / 180;
cos = Math.cos(rad);
sin = Math.sin(rad);
this.queue.push([ cos, sin, -sin, cos, 0, 0 ]);
this.cache = null;
this.translate(-rx, -ry);
}
return this;
};
Matrix.prototype.skewX = function (angle) {
if (angle !== 0) {
this.cache = null;
this.queue.push([ 1, 0, Math.tan(angle * Math.PI / 180), 1, 0, 0 ]);
}
return this;
};
Matrix.prototype.skewY = function (angle) {
if (angle !== 0) {
this.cache = null;
this.queue.push([ 1, Math.tan(angle * Math.PI / 180), 0, 1, 0, 0 ]);
}
return this;
};
// Flatten queue
//
Matrix.prototype.toArray = function () {
if (this.cache) {
return this.cache;
}
if (!this.queue.length) {
this.cache = [ 1, 0, 0, 1, 0, 0 ];
return this.cache;
}
this.cache = this.queue[0];
if (this.queue.length === 1) {
return this.cache;
}
for (var i = 1; i < this.queue.length; i++) {
this.cache = combine(this.cache, this.queue[i]);
}
return this.cache;
};
// Apply list of matrixes to (x,y) point.
// If `isRelative` set, `translate` component of matrix will be skipped
//
Matrix.prototype.calc = function (x, y, isRelative) {
var m;
// Don't change point on empty transforms queue
if (!this.queue.length) { return [ x, y ]; }
// Calculate final matrix, if not exists
//
// NB. if you deside to apply transforms to point one-by-one,
// they should be taken in reverse order
if (!this.cache) {
this.cache = this.toArray();
}
m = this.cache;
// Apply matrix to point
return [
x * m[0] + y * m[2] + (isRelative ? 0 : m[4]),
x * m[1] + y * m[3] + (isRelative ? 0 : m[5])
];
};
module.exports = Matrix;
},{}],4:[function(require,module,exports){
'use strict';
var paramCounts = { a: 7, c: 6, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, z: 0 };
var SPECIAL_SPACES = [
0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006,
0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF
];
function isSpace(ch) {
return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029) || // Line terminators
// White spaces
(ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) ||
(ch >= 0x1680 && SPECIAL_SPACES.indexOf(ch) >= 0);
}
function isCommand(code) {
/*eslint-disable no-bitwise*/
switch (code | 0x20) {
case 0x6D/* m */:
case 0x7A/* z */:
case 0x6C/* l */:
case 0x68/* h */:
case 0x76/* v */:
case 0x63/* c */:
case 0x73/* s */:
case 0x71/* q */:
case 0x74/* t */:
case 0x61/* a */:
case 0x72/* r */:
return true;
}
return false;
}
function isArc(code) {
return (code | 0x20) === 0x61;
}
function isDigit(code) {
return (code >= 48 && code <= 57); // 0..9
}
function isDigitStart(code) {
return (code >= 48 && code <= 57) || /* 0..9 */
code === 0x2B || /* + */
code === 0x2D || /* - */
code === 0x2E; /* . */
}
function State(path) {
this.index = 0;
this.path = path;
this.max = path.length;
this.result = [];
this.param = 0.0;
this.err = '';
this.segmentStart = 0;
this.data = [];
}
function skipSpaces(state) {
while (state.index < state.max && isSpace(state.path.charCodeAt(state.index))) {
state.index++;
}
}
function scanFlag(state) {
var ch = state.path.charCodeAt(state.index);
if (ch === 0x30/* 0 */) {
state.param = 0;
state.index++;
return;
}
if (ch === 0x31/* 1 */) {
state.param = 1;
state.index++;
return;
}
state.err = 'SvgPath: arc flag can be 0 or 1 only (at pos ' + state.index + ')';
}
function scanParam(state) {
var start = state.index,
index = start,
max = state.max,
zeroFirst = false,
hasCeiling = false,
hasDecimal = false,
hasDot = false,
ch;
if (index >= max) {
state.err = 'SvgPath: missed param (at pos ' + index + ')';
return;
}
ch = state.path.charCodeAt(index);
if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
index++;
ch = (index < max) ? state.path.charCodeAt(index) : 0;
}
// This logic is shamelessly borrowed from Esprima
// https://github.com/ariya/esprimas
//
if (!isDigit(ch) && ch !== 0x2E/* . */) {
state.err = 'SvgPath: param should start with 0..9 or `.` (at pos ' + index + ')';
return;
}
if (ch !== 0x2E/* . */) {
zeroFirst = (ch === 0x30/* 0 */);
index++;
ch = (index < max) ? state.path.charCodeAt(index) : 0;
if (zeroFirst && index < max) {
// decimal number starts with '0' such as '09' is illegal.
if (ch && isDigit(ch)) {
state.err = 'SvgPath: numbers started with `0` such as `09` are illegal (at pos ' + start + ')';
return;
}
}
while (index < max && isDigit(state.path.charCodeAt(index))) {
index++;
hasCeiling = true;
}
ch = (index < max) ? state.path.charCodeAt(index) : 0;
}
if (ch === 0x2E/* . */) {
hasDot = true;
index++;
while (isDigit(state.path.charCodeAt(index))) {
index++;
hasDecimal = true;
}
ch = (index < max) ? state.path.charCodeAt(index) : 0;
}
if (ch === 0x65/* e */ || ch === 0x45/* E */) {
if (hasDot && !hasCeiling && !hasDecimal) {
state.err = 'SvgPath: invalid float exponent (at pos ' + index + ')';
return;
}
index++;
ch = (index < max) ? state.path.charCodeAt(index) : 0;
if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
index++;
}
if (index < max && isDigit(state.path.charCodeAt(index))) {
while (index < max && isDigit(state.path.charCodeAt(index))) {
index++;
}
} else {
state.err = 'SvgPath: invalid float exponent (at pos ' + index + ')';
return;
}
}
state.index = index;
state.param = parseFloat(state.path.slice(start, index)) + 0.0;
}
function finalizeSegment(state) {
var cmd, cmdLC;
// Process duplicated commands (without comand name)
// This logic is shamelessly borrowed from Raphael
// https://github.com/DmitryBaranovskiy/raphael/
//
cmd = state.path[state.segmentStart];
cmdLC = cmd.toLowerCase();
var params = state.data;
if (cmdLC === 'm' && params.length > 2) {
state.result.push([ cmd, params[0], params[1] ]);
params = params.slice(2);
cmdLC = 'l';
cmd = (cmd === 'm') ? 'l' : 'L';
}
if (cmdLC === 'r') {
state.result.push([ cmd ].concat(params));
} else {
while (params.length >= paramCounts[cmdLC]) {
state.result.push([ cmd ].concat(params.splice(0, paramCounts[cmdLC])));
if (!paramCounts[cmdLC]) {
break;
}
}
}
}
function scanSegment(state) {
var max = state.max,
cmdCode, is_arc, comma_found, need_params, i;
state.segmentStart = state.index;
cmdCode = state.path.charCodeAt(state.index);
is_arc = isArc(cmdCode);
if (!isCommand(cmdCode)) {
state.err = 'SvgPath: bad command ' + state.path[state.index] + ' (at pos ' + state.index + ')';
return;
}
need_params = paramCounts[state.path[state.index].toLowerCase()];
state.index++;
skipSpaces(state);
state.data = [];
if (!need_params) {
// Z
finalizeSegment(state);
return;
}
comma_found = false;
for (;;) {
for (i = need_params; i > 0; i--) {
if (is_arc && (i === 3 || i === 4)) scanFlag(state);
else scanParam(state);
if (state.err.length) {
return;
}
state.data.push(state.param);
skipSpaces(state);
comma_found = false;
if (state.index < max && state.path.charCodeAt(state.index) === 0x2C/* , */) {
state.index++;
skipSpaces(state);
comma_found = true;
}
}
// after ',' param is mandatory
if (comma_found) {
continue;
}
if (state.index >= state.max) {
break;
}
// Stop on next segment
if (!isDigitStart(state.path.charCodeAt(state.index))) {
break;
}
}
finalizeSegment(state);
}
/* Returns array of segments:
*
* [
* [ command, coord1, coord2, ... ]
* ]
*/
module.exports = function pathParse(svgPath) {
var state = new State(svgPath);
var max = state.max;
skipSpaces(state);
while (state.index < max && !state.err.length) {
scanSegment(state);
}
if (state.err.length) {
state.result = [];
} else if (state.result.length) {
if ('mM'.indexOf(state.result[0][0]) < 0) {
state.err = 'SvgPath: string should start with `M` or `m`';
state.result = [];
} else {
state.result[0][0] = 'M';
}
}
return {
err: state.err,
segments: state.result
};
};
},{}],5:[function(require,module,exports){
// SVG Path transformations library
//
// Usage:
//
// SvgPath('...')
// .translate(-150, -100)
// .scale(0.5)
// .translate(-150, -100)
// .toFixed(1)
// .toString()
//
'use strict';
var pathParse = require('./path_parse');
var transformParse = require('./transform_parse');
var matrix = require('./matrix');
var a2c = require('./a2c');
var ellipse = require('./ellipse');
// Class constructor
//
function SvgPath(path) {
if (!(this instanceof SvgPath)) { return new SvgPath(path); }
var pstate = pathParse(path);
// Array of path segments.
// Each segment is array [command, param1, param2, ...]
this.segments = pstate.segments;
// Error message on parse error.
this.err = pstate.err;
// Transforms stack for lazy evaluation
this.__stack = [];
}
SvgPath.from = function (src) {
if (typeof src === 'string') return new SvgPath(src);
if (src instanceof SvgPath) {
// Create empty object
var s = new SvgPath('');
// Clone properies
s.err = src.err;
s.segments = src.segments.map(function (sgm) { return sgm.slice(); });
s.__stack = src.__stack.map(function (m) {
return matrix().matrix(m.toArray());
});
return s;
}
throw new Error('SvgPath.from: invalid param type ' + src);
};
SvgPath.prototype.__matrix = function (m) {
var self = this, i;
// Quick leave for empty matrix
if (!m.queue.length) { return; }
this.iterate(function (s, index, x, y) {
var p, result, name, isRelative;
switch (s[0]) {
// Process 'assymetric' commands separately
case 'v':
p = m.calc(0, s[1], true);
result = (p[0] === 0) ? [ 'v', p[1] ] : [ 'l', p[0], p[1] ];
break;
case 'V':
p = m.calc(x, s[1], false);
result = (p[0] === m.calc(x, y, false)[0]) ? [ 'V', p[1] ] : [ 'L', p[0], p[1] ];
break;
case 'h':
p = m.calc(s[1], 0, true);
result = (p[1] === 0) ? [ 'h', p[0] ] : [ 'l', p[0], p[1] ];
break;
case 'H':
p = m.calc(s[1], y, false);
result = (p[1] === m.calc(x, y, false)[1]) ? [ 'H', p[0] ] : [ 'L', p[0], p[1] ];
break;
case 'a':
case 'A':
// ARC is: ['A', rx, ry, x-axis-rotation, large-arc-flag, sweep-flag, x, y]
// Drop segment if arc is empty (end point === start point)
/*if ((s[0] === 'A' && s[6] === x && s[7] === y) ||
(s[0] === 'a' && s[6] === 0 && s[7] === 0)) {
return [];
}*/
// Transform rx, ry and the x-axis-rotation
var ma = m.toArray();
var e = ellipse(s[1], s[2], s[3]).transform(ma);
// flip sweep-flag if matrix is not orientation-preserving
if (ma[0] * ma[3] - ma[1] * ma[2] < 0) {
s[5] = s[5] ? '0' : '1';
}
// Transform end point as usual (without translation for relative notation)
p = m.calc(s[6], s[7], s[0] === 'a');
// Empty arcs can be ignored by renderer, but should not be dropped
// to avoid collisions with `S A S` and so on. Replace with empty line.
if ((s[0] === 'A' && s[6] === x && s[7] === y) ||
(s[0] === 'a' && s[6] === 0 && s[7] === 0)) {
result = [ s[0] === 'a' ? 'l' : 'L', p[0], p[1] ];
break;
}
// if the resulting ellipse is (almost) a segment ...
if (e.isDegenerate()) {
// replace the arc by a line
result = [ s[0] === 'a' ? 'l' : 'L', p[0], p[1] ];
} else {
// if it is a real ellipse
// s[0], s[4] and s[5] are not modified
result = [ s[0], e.rx, e.ry, e.ax, s[4], s[5], p[0], p[1] ];
}
break;
case 'm':
// Edge case. The very first `m` should be processed as absolute, if happens.
// Make sense for coord shift transforms.
isRelative = index > 0;
p = m.calc(s[1], s[2], isRelative);
result = [ 'm', p[0], p[1] ];
break;
default:
name = s[0];
result = [ name ];
isRelative = (name.toLowerCase() === name);
// Apply transformations to the segment
for (i = 1; i < s.length; i += 2) {
p = m.calc(s[i], s[i + 1], isRelative);
result.push(p[0], p[1]);
}
}
self.segments[index] = result;
}, true);
};
// Apply stacked commands
//
SvgPath.prototype.__evaluateStack = function () {
var m, i;
if (!this.__stack.length) { return; }
if (this.__stack.length === 1) {
this.__matrix(this.__stack[0]);
this.__stack = [];
return;
}
m = matrix();
i = this.__stack.length;
while (--i >= 0) {
m.matrix(this.__stack[i].toArray());
}
this.__matrix(m);
this.__stack = [];
};
// Convert processed SVG Path back to string
//
SvgPath.prototype.toString = function () {
var elements = [], skipCmd, cmd;
this.__evaluateStack();
for (var i = 0; i < this.segments.length; i++) {
// remove repeating commands names
cmd = this.segments[i][0];
skipCmd = i > 0 && cmd !== 'm' && cmd !== 'M' && cmd === this.segments[i - 1][0];
elements = elements.concat(skipCmd ? this.segments[i].slice(1) : this.segments[i]);
}
return elements.join(' ')
// Optimizations: remove spaces around commands & before `-`
//
// We could also remove leading zeros for `0.5`-like values,
// but their count is too small to spend time for.
.replace(/ ?([achlmqrstvz]) ?/gi, '$1')
.replace(/ \-/g, '-')
// workaround for FontForge SVG importing bug
.replace(/zm/g, 'z m');
};
// Translate path to (x [, y])
//
SvgPath.prototype.translate = function (x, y) {
this.__stack.push(matrix().translate(x, y || 0));
return this;
};
// Scale path to (sx [, sy])
// sy = sx if not defined
//
SvgPath.prototype.scale = function (sx, sy) {
this.__stack.push(matrix().scale(sx, (!sy && (sy !== 0)) ? sx : sy));
return this;
};
// Rotate path around point (sx [, sy])
// sy = sx if not defined
//
SvgPath.prototype.rotate = function (angle, rx, ry) {
this.__stack.push(matrix().rotate(angle, rx || 0, ry || 0));
return this;
};
// Skew path along the X axis by `degrees` angle
//
SvgPath.prototype.skewX = function (degrees) {
this.__stack.push(matrix().skewX(degrees));
return this;
};