-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsvg.js
4324 lines (3625 loc) · 108 KB
/
svg.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
/*!
* svg.js - A lightweight library for manipulating and animating SVG.
* @version 2.0.5
* http://www.svgjs.com
*
* @copyright Wout Fierens <wout@impinc.co.uk>
* @license MIT
*
* BUILT: Sun Jul 05 2015 01:42:48 GMT+0200 (Mitteleuropaische Sommerzeit)
*/;
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof exports === 'object') {
module.exports = factory(require, exports, module);
} else {
root.SVG = factory();
}
}(this, function(require, exports, module) {
// The main wrapping element
var SVG = this.SVG = function(element) {
if (SVG.supported) {
element = new SVG.Doc(element)
if (!SVG.parser)
SVG.prepare(element)
return element
}
}
// Default namespaces
SVG.ns = 'http://www.w3.org/2000/svg'
SVG.xmlns = 'http://www.w3.org/2000/xmlns/'
SVG.xlink = 'http://www.w3.org/1999/xlink'
// Svg support test
SVG.supported = (function() {
return !! document.createElementNS &&
!! document.createElementNS(SVG.ns,'svg').createSVGRect
})()
// Don't bother to continue if SVG is not supported
if (!SVG.supported) return false
// Element id sequence
SVG.did = 1000
// Get next named element id
SVG.eid = function(name) {
return 'Svgjs' + capitalize(name) + (SVG.did++)
}
// Method for element creation
SVG.create = function(name) {
// create element
var element = document.createElementNS(this.ns, name)
// apply unique id
element.setAttribute('id', this.eid(name))
return element
}
// Method for extending objects
SVG.extend = function() {
var modules, methods, key, i
// Get list of modules
modules = [].slice.call(arguments)
// Get object with extensions
methods = modules.pop()
for (i = modules.length - 1; i >= 0; i--)
if (modules[i])
for (key in methods)
modules[i].prototype[key] = methods[key]
// Make sure SVG.Set inherits any newly added methods
if (SVG.Set && SVG.Set.inherit)
SVG.Set.inherit()
}
// Invent new element
SVG.invent = function(config) {
// Create element initializer
var initializer = typeof config.create == 'function' ?
config.create :
function() {
this.constructor.call(this, SVG.create(config.create))
}
// Inherit prototype
if (config.inherit)
initializer.prototype = new config.inherit
// Extend with methods
if (config.extend)
SVG.extend(initializer, config.extend)
// Attach construct method to parent
if (config.construct)
SVG.extend(config.parent || SVG.Container, config.construct)
return initializer
}
// Adopt existing svg elements
SVG.adopt = function(node) {
// make sure a node isn't already adopted
if (node.instance) return node.instance
// initialize variables
var element
// adopt with element-specific settings
if (node.nodeName == 'svg')
element = node.parentNode instanceof SVGElement ? new SVG.Nested : new SVG.Doc
else if (node.nodeName == 'lineairGradient') // lineair?
element = new SVG.Gradient('lineair')
else if (node.nodeName == 'radialGradient')
element = new SVG.Gradient('radial')
else if (SVG[capitalize(node.nodeName)])
element = new SVG[capitalize(node.nodeName)]
else
element = new SVG.Element(node)
// ensure references
element.type = node.nodeName
element.node = node
node.instance = element
// SVG.Class specific preparations
if (element instanceof SVG.Doc)
element.namespace().defs()
return element
}
// Initialize parsing element
SVG.prepare = function(element) {
// Select document body and create invisible svg element
var body = document.getElementsByTagName('body')[0]
, draw = (body ? new SVG.Doc(body) : element.nested()).size(2, 0)
, path = SVG.create('path')
// Insert parsers
draw.node.appendChild(path)
// Create parser object
SVG.parser = {
body: body || element.parent()
, draw: draw.style('opacity:0;position:fixed;left:100%;top:100%;overflow:hidden')
, poly: draw.polyline().node
, path: path
}
}
// Storage for regular expressions
SVG.regex = {
// Parse unit value
unit: /^(-?[\d\.]+)([a-z%]{0,2})$/
// Parse hex value
, hex: /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i
// Parse rgb value
, rgb: /rgb\((\d+),(\d+),(\d+)\)/
// Parse reference id
, reference: /#([a-z0-9\-_]+)/i
// Parse matrix wrapper
, matrix: /matrix\(|\)/g
// Whitespace
, whitespace: /\s/g
// Test hex value
, isHex: /^#[a-f0-9]{3,6}$/i
// Test rgb value
, isRgb: /^rgb\(/
// Test css declaration
, isCss: /[^:]+:[^;]+;?/
// Test for blank string
, isBlank: /^(\s+)?$/
// Test for numeric string
, isNumber: /^-?[\d\.]+$/
// Test for percent value
, isPercent: /^-?[\d\.]+%$/
// Test for image url
, isImage: /\.(jpg|jpeg|png|gif|svg)(\?[^=]+.*)?/i
}
SVG.utils = {
// Map function
map: function(array, block) {
var i
, il = array.length
, result = []
for (i = 0; i < il; i++)
result.push(block(array[i]))
return result
}
// Degrees to radians
, radians: function(d) {
return d % 360 * Math.PI / 180
}
// Radians to degrees
, degrees: function(r) {
return r * 180 / Math.PI % 360
}
, filterSVGElements: function(p) {
return [].filter.call(p, function(el){ return el instanceof SVGElement })
}
}
SVG.defaults = {
// Default attribute values
attrs: {
/* fill and stroke */
'fill-opacity': 1
, 'stroke-opacity': 1
, 'stroke-width': 0
, 'stroke-linejoin': 'miter'
, 'stroke-linecap': 'butt'
, fill: '#000000'
, stroke: '#000000'
, opacity: 1
/* position */
, x: 0
, y: 0
, cx: 0
, cy: 0
/* size */
, width: 0
, height: 0
/* radius */
, r: 0
, rx: 0
, ry: 0
/* gradient */
, offset: 0
, 'stop-opacity': 1
, 'stop-color': '#000000'
/* text */
, 'font-size': 16
, 'font-family': 'Helvetica, Arial, sans-serif'
, 'text-anchor': 'start'
}
}
// Module for color convertions
SVG.Color = function(color) {
var match
/* initialize defaults */
this.r = 0
this.g = 0
this.b = 0
/* parse color */
if (typeof color === 'string') {
if (SVG.regex.isRgb.test(color)) {
/* get rgb values */
match = SVG.regex.rgb.exec(color.replace(/\s/g,''))
/* parse numeric values */
this.r = parseInt(match[1])
this.g = parseInt(match[2])
this.b = parseInt(match[3])
} else if (SVG.regex.isHex.test(color)) {
/* get hex values */
match = SVG.regex.hex.exec(fullHex(color))
/* parse numeric values */
this.r = parseInt(match[1], 16)
this.g = parseInt(match[2], 16)
this.b = parseInt(match[3], 16)
}
} else if (typeof color === 'object') {
this.r = color.r
this.g = color.g
this.b = color.b
}
}
SVG.extend(SVG.Color, {
// Default to hex conversion
toString: function() {
return this.toHex()
}
// Build hex value
, toHex: function() {
return '#'
+ compToHex(this.r)
+ compToHex(this.g)
+ compToHex(this.b)
}
// Build rgb value
, toRgb: function() {
return 'rgb(' + [this.r, this.g, this.b].join() + ')'
}
// Calculate true brightness
, brightness: function() {
return (this.r / 255 * 0.30)
+ (this.g / 255 * 0.59)
+ (this.b / 255 * 0.11)
}
// Make color morphable
, morph: function(color) {
this.destination = new SVG.Color(color)
return this
}
// Get morphed color at given position
, at: function(pos) {
/* make sure a destination is defined */
if (!this.destination) return this
/* normalise pos */
pos = pos < 0 ? 0 : pos > 1 ? 1 : pos
/* generate morphed color */
return new SVG.Color({
r: ~~(this.r + (this.destination.r - this.r) * pos)
, g: ~~(this.g + (this.destination.g - this.g) * pos)
, b: ~~(this.b + (this.destination.b - this.b) * pos)
})
}
})
// Testers
// Test if given value is a color string
SVG.Color.test = function(color) {
color += ''
return SVG.regex.isHex.test(color)
|| SVG.regex.isRgb.test(color)
}
// Test if given value is a rgb object
SVG.Color.isRgb = function(color) {
return color && typeof color.r == 'number'
&& typeof color.g == 'number'
&& typeof color.b == 'number'
}
// Test if given value is a color
SVG.Color.isColor = function(color) {
return SVG.Color.isRgb(color) || SVG.Color.test(color)
}
// Module for array conversion
SVG.Array = function(array, fallback) {
array = (array || []).valueOf()
/* if array is empty and fallback is provided, use fallback */
if (array.length == 0 && fallback)
array = fallback.valueOf()
/* parse array */
this.value = this.parse(array)
}
SVG.extend(SVG.Array, {
// Make array morphable
morph: function(array) {
this.destination = this.parse(array)
/* normalize length of arrays */
if (this.value.length != this.destination.length) {
var lastValue = this.value[this.value.length - 1]
, lastDestination = this.destination[this.destination.length - 1]
while(this.value.length > this.destination.length)
this.destination.push(lastDestination)
while(this.value.length < this.destination.length)
this.value.push(lastValue)
}
return this
}
// Clean up any duplicate points
, settle: function() {
/* find all unique values */
for (var i = 0, il = this.value.length, seen = []; i < il; i++)
if (seen.indexOf(this.value[i]) == -1)
seen.push(this.value[i])
/* set new value */
return this.value = seen
}
// Get morphed array at given position
, at: function(pos) {
/* make sure a destination is defined */
if (!this.destination) return this
/* generate morphed array */
for (var i = 0, il = this.value.length, array = []; i < il; i++)
array.push(this.value[i] + (this.destination[i] - this.value[i]) * pos)
return new SVG.Array(array)
}
// Convert array to string
, toString: function() {
return this.value.join(' ')
}
// Real value
, valueOf: function() {
return this.value
}
// Parse whitespace separated string
, parse: function(array) {
array = array.valueOf()
/* if already is an array, no need to parse it */
if (Array.isArray(array)) return array
return this.split(array)
}
// Strip unnecessary whitespace
, split: function(string) {
return string.trim().split(/\s+/)
}
// Reverse array
, reverse: function() {
this.value.reverse()
return this
}
})
// Poly points array
SVG.PointArray = function(array, fallback) {
this.constructor.call(this, array, fallback || [[0,0]])
}
// Inherit from SVG.Array
SVG.PointArray.prototype = new SVG.Array
SVG.extend(SVG.PointArray, {
// Convert array to string
toString: function() {
/* convert to a poly point string */
for (var i = 0, il = this.value.length, array = []; i < il; i++)
array.push(this.value[i].join(','))
return array.join(' ')
}
// Convert array to line object
, toLine: function() {
return {
x1: this.value[0][0]
, y1: this.value[0][1]
, x2: this.value[1][0]
, y2: this.value[1][1]
}
}
// Get morphed array at given position
, at: function(pos) {
/* make sure a destination is defined */
if (!this.destination) return this
/* generate morphed point string */
for (var i = 0, il = this.value.length, array = []; i < il; i++)
array.push([
this.value[i][0] + (this.destination[i][0] - this.value[i][0]) * pos
, this.value[i][1] + (this.destination[i][1] - this.value[i][1]) * pos
])
return new SVG.PointArray(array)
}
// Parse point string
, parse: function(array) {
array = array.valueOf()
/* if already is an array, no need to parse it */
if (Array.isArray(array)) return array
/* split points */
array = this.split(array)
/* parse points */
for (var i = 0, il = array.length, p, points = []; i < il; i++) {
p = array[i].split(',')
points.push([parseFloat(p[0]), parseFloat(p[1])])
}
return points
}
// Move point string
, move: function(x, y) {
var box = this.bbox()
/* get relative offset */
x -= box.x
y -= box.y
/* move every point */
if (!isNaN(x) && !isNaN(y))
for (var i = this.value.length - 1; i >= 0; i--)
this.value[i] = [this.value[i][0] + x, this.value[i][1] + y]
return this
}
// Resize poly string
, size: function(width, height) {
var i, box = this.bbox()
/* recalculate position of all points according to new size */
for (i = this.value.length - 1; i >= 0; i--) {
this.value[i][0] = ((this.value[i][0] - box.x) * width) / box.width + box.x
this.value[i][1] = ((this.value[i][1] - box.y) * height) / box.height + box.y
}
return this
}
// Get bounding box of points
, bbox: function() {
SVG.parser.poly.setAttribute('points', this.toString())
return SVG.parser.poly.getBBox()
}
})
// Path points array
SVG.PathArray = function(array, fallback) {
this.constructor.call(this, array, fallback || [['M', 0, 0]])
}
// Inherit from SVG.Array
SVG.PathArray.prototype = new SVG.Array
SVG.extend(SVG.PathArray, {
// Convert array to string
toString: function() {
return arrayToString(this.value)
}
// Move path string
, move: function(x, y) {
/* get bounding box of current situation */
var box = this.bbox()
/* get relative offset */
x -= box.x
y -= box.y
if (!isNaN(x) && !isNaN(y)) {
/* move every point */
for (var l, i = this.value.length - 1; i >= 0; i--) {
l = this.value[i][0]
if (l == 'M' || l == 'L' || l == 'T') {
this.value[i][1] += x
this.value[i][2] += y
} else if (l == 'H') {
this.value[i][1] += x
} else if (l == 'V') {
this.value[i][1] += y
} else if (l == 'C' || l == 'S' || l == 'Q') {
this.value[i][1] += x
this.value[i][2] += y
this.value[i][3] += x
this.value[i][4] += y
if (l == 'C') {
this.value[i][5] += x
this.value[i][6] += y
}
} else if (l == 'A') {
this.value[i][6] += x
this.value[i][7] += y
}
}
}
return this
}
// Resize path string
, size: function(width, height) {
/* get bounding box of current situation */
var i, l, box = this.bbox()
/* recalculate position of all points according to new size */
for (i = this.value.length - 1; i >= 0; i--) {
l = this.value[i][0]
if (l == 'M' || l == 'L' || l == 'T') {
this.value[i][1] = ((this.value[i][1] - box.x) * width) / box.width + box.x
this.value[i][2] = ((this.value[i][2] - box.y) * height) / box.height + box.y
} else if (l == 'H') {
this.value[i][1] = ((this.value[i][1] - box.x) * width) / box.width + box.x
} else if (l == 'V') {
this.value[i][1] = ((this.value[i][1] - box.y) * height) / box.height + box.y
} else if (l == 'C' || l == 'S' || l == 'Q') {
this.value[i][1] = ((this.value[i][1] - box.x) * width) / box.width + box.x
this.value[i][2] = ((this.value[i][2] - box.y) * height) / box.height + box.y
this.value[i][3] = ((this.value[i][3] - box.x) * width) / box.width + box.x
this.value[i][4] = ((this.value[i][4] - box.y) * height) / box.height + box.y
if (l == 'C') {
this.value[i][5] = ((this.value[i][5] - box.x) * width) / box.width + box.x
this.value[i][6] = ((this.value[i][6] - box.y) * height) / box.height + box.y
}
} else if (l == 'A') {
/* resize radii */
this.value[i][1] = (this.value[i][1] * width) / box.width
this.value[i][2] = (this.value[i][2] * height) / box.height
/* move position values */
this.value[i][6] = ((this.value[i][6] - box.x) * width) / box.width + box.x
this.value[i][7] = ((this.value[i][7] - box.y) * height) / box.height + box.y
}
}
return this
}
// Absolutize and parse path to array
, parse: function(array) {
/* if it's already is a patharray, no need to parse it */
if (array instanceof SVG.PathArray) return array.valueOf()
/* prepare for parsing */
var i, il, x0, y0, x1, y1, x2, y2, s, seg, segs
, x = 0
, y = 0
/* populate working path */
SVG.parser.path.setAttribute('d', typeof array === 'string' ? array : arrayToString(array))
/* get segments */
segs = SVG.parser.path.pathSegList
for (i = 0, il = segs.numberOfItems; i < il; ++i) {
seg = segs.getItem(i)
s = seg.pathSegTypeAsLetter
/* yes, this IS quite verbose but also about 30 times faster than .test() with a precompiled regex */
if (s == 'M' || s == 'L' || s == 'H' || s == 'V' || s == 'C' || s == 'S' || s == 'Q' || s == 'T' || s == 'A') {
if ('x' in seg) x = seg.x
if ('y' in seg) y = seg.y
} else {
if ('x1' in seg) x1 = x + seg.x1
if ('x2' in seg) x2 = x + seg.x2
if ('y1' in seg) y1 = y + seg.y1
if ('y2' in seg) y2 = y + seg.y2
if ('x' in seg) x += seg.x
if ('y' in seg) y += seg.y
if (s == 'm')
segs.replaceItem(SVG.parser.path.createSVGPathSegMovetoAbs(x, y), i)
else if (s == 'l')
segs.replaceItem(SVG.parser.path.createSVGPathSegLinetoAbs(x, y), i)
else if (s == 'h')
segs.replaceItem(SVG.parser.path.createSVGPathSegLinetoHorizontalAbs(x), i)
else if (s == 'v')
segs.replaceItem(SVG.parser.path.createSVGPathSegLinetoVerticalAbs(y), i)
else if (s == 'c')
segs.replaceItem(SVG.parser.path.createSVGPathSegCurvetoCubicAbs(x, y, x1, y1, x2, y2), i)
else if (s == 's')
segs.replaceItem(SVG.parser.path.createSVGPathSegCurvetoCubicSmoothAbs(x, y, x2, y2), i)
else if (s == 'q')
segs.replaceItem(SVG.parser.path.createSVGPathSegCurvetoQuadraticAbs(x, y, x1, y1), i)
else if (s == 't')
segs.replaceItem(SVG.parser.path.createSVGPathSegCurvetoQuadraticSmoothAbs(x, y), i)
else if (s == 'a')
segs.replaceItem(SVG.parser.path.createSVGPathSegArcAbs(x, y, seg.r1, seg.r2, seg.angle, seg.largeArcFlag, seg.sweepFlag), i)
else if (s == 'z' || s == 'Z') {
x = x0
y = y0
}
}
/* record the start of a subpath */
if (s == 'M' || s == 'm') {
x0 = x
y0 = y
}
}
/* build internal representation */
array = []
segs = SVG.parser.path.pathSegList
for (i = 0, il = segs.numberOfItems; i < il; ++i) {
seg = segs.getItem(i)
s = seg.pathSegTypeAsLetter
x = [s]
if (s == 'M' || s == 'L' || s == 'T')
x.push(seg.x, seg.y)
else if (s == 'H')
x.push(seg.x)
else if (s == 'V')
x.push(seg.y)
else if (s == 'C')
x.push(seg.x1, seg.y1, seg.x2, seg.y2, seg.x, seg.y)
else if (s == 'S')
x.push(seg.x2, seg.y2, seg.x, seg.y)
else if (s == 'Q')
x.push(seg.x1, seg.y1, seg.x, seg.y)
else if (s == 'A')
x.push(seg.r1, seg.r2, seg.angle, seg.largeArcFlag | 0, seg.sweepFlag | 0, seg.x, seg.y)
/* store segment */
array.push(x)
}
return array
}
// Get bounding box of path
, bbox: function() {
SVG.parser.path.setAttribute('d', this.toString())
return SVG.parser.path.getBBox()
}
})
// Module for unit convertions
SVG.Number = SVG.invent({
// Initialize
create: function(value, unit) {
// initialize defaults
this.value = 0
this.unit = unit || ''
// parse value
if (typeof value === 'number') {
// ensure a valid numeric value
this.value = isNaN(value) ? 0 : !isFinite(value) ? (value < 0 ? -3.4e+38 : +3.4e+38) : value
} else if (typeof value === 'string') {
unit = value.match(SVG.regex.unit)
if (unit) {
// make value numeric
this.value = parseFloat(unit[1])
// normalize
if (unit[2] == '%')
this.value /= 100
else if (unit[2] == 's')
this.value *= 1000
// store unit
this.unit = unit[2]
}
} else {
if (value instanceof SVG.Number) {
this.value = value.valueOf()
this.unit = value.unit
}
}
}
// Add methods
, extend: {
// Stringalize
toString: function() {
return (
this.unit == '%' ?
~~(this.value * 1e8) / 1e6:
this.unit == 's' ?
this.value / 1e3 :
this.value
) + this.unit
}
, // Convert to primitive
valueOf: function() {
return this.value
}
// Add number
, plus: function(number) {
return new SVG.Number(this + new SVG.Number(number), this.unit)
}
// Subtract number
, minus: function(number) {
return this.plus(-new SVG.Number(number))
}
// Multiply number
, times: function(number) {
return new SVG.Number(this * new SVG.Number(number), this.unit)
}
// Divide number
, divide: function(number) {
return new SVG.Number(this / new SVG.Number(number), this.unit)
}
// Convert to different unit
, to: function(unit) {
var number = new SVG.Number(this)
if (typeof unit === 'string')
number.unit = unit
return number
}
// Make number morphable
, morph: function(number) {
this.destination = new SVG.Number(number)
return this
}
// Get morphed number at given position
, at: function(pos) {
// Make sure a destination is defined
if (!this.destination) return this
// Generate new morphed number
return new SVG.Number(this.destination)
.minus(this)
.times(pos)
.plus(this)
}
}
})
SVG.ViewBox = function(element) {
var x, y, width, height
, wm = 1 /* width multiplier */
, hm = 1 /* height multiplier */
, box = element.bbox()
, view = (element.attr('viewBox') || '').match(/-?[\d\.]+/g)
, we = element
, he = element
/* get dimensions of current node */
width = new SVG.Number(element.width())
height = new SVG.Number(element.height())
/* find nearest non-percentual dimensions */
while (width.unit == '%') {
wm *= width.value
width = new SVG.Number(we instanceof SVG.Doc ? we.parent().offsetWidth : we.parent().width())
we = we.parent()
}
while (height.unit == '%') {
hm *= height.value
height = new SVG.Number(he instanceof SVG.Doc ? he.parent().offsetHeight : he.parent().height())
he = he.parent()
}
/* ensure defaults */
this.x = box.x
this.y = box.y
this.width = width * wm
this.height = height * hm
this.zoom = 1
if (view) {
/* get width and height from viewbox */
x = parseFloat(view[0])
y = parseFloat(view[1])
width = parseFloat(view[2])
height = parseFloat(view[3])
/* calculate zoom accoring to viewbox */
this.zoom = ((this.width / this.height) > (width / height)) ?
this.height / height :
this.width / width
/* calculate real pixel dimensions on parent SVG.Doc element */
this.x = x
this.y = y
this.width = width
this.height = height
}
}
//
SVG.extend(SVG.ViewBox, {
// Parse viewbox to string
toString: function() {
return this.x + ' ' + this.y + ' ' + this.width + ' ' + this.height
}
})
SVG.Element = SVG.invent({
// Initialize node
create: function(node) {
// make stroke value accessible dynamically
this._stroke = SVG.defaults.attrs.stroke
// create circular reference
if (this.node = node) {
this.type = node.nodeName
this.node.instance = this
// store current attribute value
this._stroke = node.getAttribute('stroke') || this._stroke
}
}
// Add class methods
, extend: {
// Move over x-axis
x: function(x) {
return this.attr('x', x)
}
// Move over y-axis
, y: function(y) {
return this.attr('y', y)
}
// Move by center over x-axis
, cx: function(x) {
return x == null ? this.x() + this.width() / 2 : this.x(x - this.width() / 2)
}
// Move by center over y-axis
, cy: function(y) {
return y == null ? this.y() + this.height() / 2 : this.y(y - this.height() / 2)
}
// Move element to given x and y values
, move: function(x, y) {
return this.x(x).y(y)
}
// Move element by its center
, center: function(x, y) {
return this.cx(x).cy(y)
}
// Set width of element
, width: function(width) {
return this.attr('width', width)
}
// Set height of element
, height: function(height) {
return this.attr('height', height)
}
// Set element size to given width and height
, size: function(width, height) {
var p = proportionalSize(this.bbox(), width, height)
return this
.width(new SVG.Number(p.width))
.height(new SVG.Number(p.height))
}
// Clone element
, clone: function() {
// clone element and assign new id
var clone = assignNewId(this.node.cloneNode(true))
// insert the clone after myself
this.after(clone)
return clone
}
// Remove element
, remove: function() {
if (this.parent())
this.parent().removeElement(this)
return this
}
// Replace element
, replace: function(element) {
this.after(element).remove()
return element
}
// Add element to given container and return self
, addTo: function(parent) {
return parent.put(this)
}
// Add element to given container and return container
, putIn: function(parent) {
return parent.add(this)
}
// Get / set id