forked from maxwellito/vivus
-
Notifications
You must be signed in to change notification settings - Fork 3
/
vivus-patched3.js
925 lines (846 loc) · 25.9 KB
/
vivus-patched3.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
/**
* vivus - JavaScript library to make drawing animation on SVG
* @version v0.1.2
* @link https://github.com/maxwellito/vivus
* @license MIT
*/
'use strict';
(function () {
var _checkElm = function(elm){
/*
console.log('VIVUS _checkElm:');
console.log('toString: '+elm.constructor.toString());
console.log(elm);
console.log('typeof: '+typeof elm);
console.log('hasOwnProperty: '+elm.hasOwnProperty('nodeName'));
console.log('typeof element.nodeName: '+typeof elm.nodeName);
console.log('element.nodeName: '+elm.nodeName.toLowerCase());
*/
if (elm.constructor === SVGSVGElement) {
console.info('_checkElm passed on SVGSVGElement');
return true;
}
if ( typeof elm === 'object' && typeof elm.nodeName !== 'undefined' && elm.nodeName.toLowerCase() === 'svg') {
console.warn('_checkElm passed on ObjectElement');
return true;
}
return false;
};
'use strict';
/**
* Pathformer
* Beta version
*
* Take any SVG version 1.1 and transform
* child elements to 'path' elements
*
* This code is purely forked from
* https://github.com/Waest/SVGPathConverter
*/
/**
* Class constructor
*
* @param {DOM|String} element Dom element of the SVG or id of it
*/
function Pathformer(element) {
// Test params
if (typeof element === 'undefined') {
throw new Error('Pathformer [constructor]: "element" parameter is required');
}
// Set the element
if (element.constructor === String) {
element = document.getElementById(element);
if (!element) {
throw new Error('Pathformer [constructor]: "element" parameter is not related to an existing ID');
}
}
// if (element.constructor === SVGSVGElement || element.constructor === 'SVGSVGElementConstructor') {
else {
if ( _checkElm(element) ) {
this.el = element;
} else {
throw new Error('Pathformer [constructor]: "element" parameter must be a string or a SVGelement');
}
}
// Start
this.scan(element);
}
/**
* List of tags which can be transformed
* to path elements
*
* @type {Array}
*/
Pathformer.prototype.TYPES = ['line', 'elipse', 'circle', 'polygon', 'polyline', 'rect'];
/**
* List of attribute names which contain
* data. This array list them to check if
* they contain bad values, like percentage.
*
* @type {Array}
*/
Pathformer.prototype.ATTR_WATCH = ['cx', 'cy', 'points', 'r', 'rx', 'ry', 'x', 'x1', 'x2', 'y', 'y1', 'y2'];
/**
* Finds the elements compatible for transform
* and apply the liked method
*
* @param {object} options Object from the constructor
*/
Pathformer.prototype.scan = function (svg) {
var fn, element, pathData, pathDom,
elements = svg.querySelectorAll(this.TYPES.join(','));
for (var i = 0; i < elements.length; i++) {
element = elements[i];
fn = this[element.tagName.toLowerCase() + 'ToPath'];
pathData = fn(this.parseAttr(element.attributes));
pathDom = this.pathMaker(element, pathData);
element.parentNode.replaceChild(pathDom, element);
}
};
/**
* Read `line` element to extract and transform
* data, to make it ready for a `path` object.
*
* @param {DOMelement} element Line element to transform
* @return {object} Data for a `path` element
*/
Pathformer.prototype.lineToPath = function (element) {
var newElement = {};
newElement.d = 'M' + element.x1 + ',' + element.y1 + 'L' + element.x2 + ',' + element.y2;
return newElement;
};
/**
* Read `rect` element to extract and transform
* data, to make it ready for a `path` object.
* The radius-border is not taken in charge yet.
* (your help is more than welcomed)
*
* @param {DOMelement} element Rect element to transform
* @return {object} Data for a `path` element
*/
Pathformer.prototype.rectToPath = function (element) {
var newElement = {},
x = parseFloat(element.x) || 0,
y = parseFloat(element.y) || 0,
width = parseFloat(element.width) || 0,
height = parseFloat(element.height) || 0;
newElement.d = 'M' + x + ' ' + y + ' ';
newElement.d += 'L' + (x + width) + ' ' + y + ' ';
newElement.d += 'L' + (x + width) + ' ' + (y + height) + ' ';
newElement.d += 'L' + x + ' ' + (y + height) + ' Z';
return newElement;
};
/**
* Read `polyline` element to extract and transform
* data, to make it ready for a `path` object.
*
* @param {DOMelement} element Polyline element to transform
* @return {object} Data for a `path` element
*/
Pathformer.prototype.polylineToPath = function (element) {
var newElement = {};
var points = element.points.split(' ');
var path = 'M' + points[0];
for(var i = 1; i < points.length; i++) {
if (points[i].indexOf(',') !== -1) {
path += 'L'+points[i];
}
}
newElement.d = path;
return newElement;
};
/**
* Read `polygon` element to extract and transform
* data, to make it ready for a `path` object.
* This method rely on polylineToPath, because the
* logic is similar. THe path created is just closed,
* so it needs an 'Z' at the end.
*
* @param {DOMelement} element Polygon element to transform
* @return {object} Data for a `path` element
*/
Pathformer.prototype.polygonToPath = function (element) {
var newElement = Pathformer.prototype.polylineToPath(element);
newElement.d += 'Z';
return newElement;
};
/**
* Read `elipse` element to extract and transform
* data, to make it ready for a `path` object.
*
* @param {DOMelement} element Elipse element to transform
* @return {object} Data for a `path` element
*/
Pathformer.prototype.elipseToPath = function (element) {
var startX = element.cx - element.rx,
startY = element.cy;
var endX = parseFloat(element.cx) + parseFloat(element.rx),
endY = element.cy;
var newElement = {};
newElement.d = 'M' + startX + ',' + startY +
'A' + element.rx + ',' + element.ry + ' 0,1,1 ' + endX + ',' + endY +
'A' + element.rx + ',' + element.ry + ' 0,1,1 ' + startX + ',' + endY;
return newElement;
};
/**
* Read `circle` element to extract and transform
* data, to make it ready for a `path` object.
*
* @param {DOMelement} element Circle element to transform
* @return {object} Data for a `path` element
*/
Pathformer.prototype.circleToPath = function (element) {
var newElement = {};
var startX = element.cx - element.r,
startY = element.cy;
var endX = parseFloat(element.cx) + parseFloat(element.r),
endY = element.cy;
newElement.d = 'M' + startX + ',' + startY +
'A' + element.r + ',' + element.r + ' 0,1,1 ' + endX + ',' + endY +
'A' + element.r + ',' + element.r + ' 0,1,1 ' + startX + ',' + endY;
return newElement;
};
/**
* Create `path` elements form original element
* and prepared objects
*
* @param {DOMelement} element Original element to transform
* @param {object} pathData Path data (from `toPath` methods)
* @return {DOMelement} Path element
*/
Pathformer.prototype.pathMaker = function (element, pathData) {
var i, attr, pathTag = document.createElementNS('http://www.w3.org/2000/svg','path');
for(i = 0; i < element.attributes.length; i++) {
attr = element.attributes[i];
if (this.ATTR_WATCH.indexOf(attr.name) === -1) {
pathTag.setAttribute(attr.name, attr.value);
}
}
for(i in pathData) {
pathTag.setAttribute(i, pathData[i]);
}
return pathTag;
};
/**
* Parse attributes of a DOM element to
* get an object of attribute => value
*
* @param {NamedNodeMap} attributes Attributes object from DOM element to parse
* @return {object} Object of attributes
*/
Pathformer.prototype.parseAttr = function (element) {
var attr, output = {};
for (var i = 0; i < element.length; i++) {
attr = element[i];
// Check if no data attribute contains '%', or the transformation is impossible
if (this.ATTR_WATCH.indexOf(attr.name) !== -1 && attr.value.indexOf('%') !== -1) {
throw new Error('Pathformer [parseAttr]: a SVG shape got values in percentage. This cannot be transformed into \'path\' tags. Please use \'viewBox\'.');
}
output[attr.name] = attr.value;
}
return output;
};
'use strict';
var requestAnimFrame, cancelAnimFrame, parsePositiveInt;
/**
* Vivus
* Beta version
*
* Take any SVG and make the animation
* to give give the impression of live drawing
*
* This in more than just inspired from codrops
* At that point, it's a pure fork.
*/
/**
* Class constructor
* option structure
* type: 'delayed'|'async'|'oneByOne'|'script' (to know if the item must be drawn asynchronously or not, default: delayed)
* duration: <int> (in frames)
* start: 'inViewport'|'manual'|'autostart' (start automatically the animation, default: inViewport)
* delay: <int> (delay between the drawing of first and last path)
*
* The attribute 'type' is by default on 'delayed'.
* - 'delayed'
* all paths are draw at the same time but with a
* little delay between them before start
* - 'async'
* all path are start and finish at the same time
* - 'oneByOne'
* only one path is draw at the time
* the end of the first one will trigger the draw
* of the next one
*
* All these values can be overwritten individually
* for each path item in the SVG
* The value of frames will always take the advantage of
* the duration value.
* If you fail somewhere, an error will be thrown.
* Good luck.
*
* @constructor
* @this {Vivus}
* @param {DOM|String} element Dom element of the SVG or id of it
* @param {Object} options Options about the animation
* @param {Function} callback Callback for the end of the animation
*/
var isReady = false;
function Vivus (element, options, callback) {
var self = this;
this.setElement(element);
var _init = function(){
// Setup
self.setOptions(options);
self.setCallback(callback);
// Set object variables
self.frameLength = 0;
self.currentFrame = 0;
self.map = [];
new Pathformer(element);
self.mapping();
self.starter();
isReady = true;
if ( typeof options.onReady !== 'undefined' && typeof options.onReady === 'function'){
options.onReady.call(self);
}
};
var addLoadEventOnElement = function(){
self.el.addEventListener('load', function(e){
element = e.target.contentDocument;
var svgElements = element.getElementsByTagName('svg');
if ( 0 === svgElements.length ) {
throw new Error('Vivus: there is no <svg> element in this <object>.');
}
else {
element = self.el = svgElements[0];
_init();
}
});
};
if ( this.el ) {
switch ( this.el.nodeName.toLowerCase() ){
case 'object':
addLoadEventOnElement();
break;
case 'svg':
_init();
break;
default: // no supported element or create one
if ( typeof options.file !== 'undefined' ) {
var objElm = document.createElement('object');
objElm.setAttribute('type', 'image/svg+xml');
objElm.setAttribute('data', options.file);
this.el.appendChild(objElm);
this.el = objElm;
addLoadEventOnElement();
}
else {
throw new Error('Vivus can\'t work on this type of element.');
}
}
}
}
Vivus.prototype.isReady = function(){
return isReady;
}
/**
* Setters
**************************************
*/
/**
* Check and set the element in the instance
* The method will not return anything, but will throw an
* error if the parameter is invalid
*
* @param {DOM|String} element SVG Dom element or id of it
*/
Vivus.prototype.setElement = function (element) {
// Basic check
if (typeof element === 'undefined') {
throw new Error('Vivus [constructor]: "element" parameter is required');
}
// Set the element
if (element.constructor === String) {
element = document.getElementById(element);
if (!element) {
throw new Error('Vivus [constructor]: "element" parameter is not related to an existing ID');
}
else {
this.el = element;
}
}
else {
// if (element.constructor === SVGSVGElement || element.constructor === 'SVGSVGElementConstructor') {
if ( _checkElm(element) ) {
this.el = element;
} else {
throw new Error('Vivus [constructor]: "element" parameter must be a string or a SVGelement');
}
}
};
/**
* Set up user option to the instance
* The method will not return anything, but will throw an
* error if the parameter is invalid
*
* @param {object} options Object from the constructor
*/
Vivus.prototype.setType = function (type) {
var allowedTypes = ['delayed', 'async', 'oneByOne', 'scenario', 'scenario-sync'];
// Set the animation type
if (type && allowedTypes.indexOf(type) === -1) {
throw new Error('Vivus [constructor]: ' + type + ' is not an existing animation `type`');
}
else {
this.type = type || allowedTypes[0];
}
this.map=[];
this.mapping();
return this;
};
Vivus.prototype.setStrokeColor = function(hexColorAsString){
if ( 0 === this.map.length || typeof hexColorAsString === 'undefined') {
return this;
}
for ( var i=0; i < this.map.length; i++ ){
if ( this.map[i].el ) {
this.map[i].el.setAttribute( 'stroke', hexColorAsString );
}
}
return this;
};
Vivus.prototype.setOptions = function (options) {
var allowedTypes = ['delayed', 'async', 'oneByOne', 'scenario', 'scenario-sync'];
var allowedStarts = ['inViewport', 'manual', 'autostart'];
// Basic check
if (options !== undefined && options.constructor !== Object) {
throw new Error('Vivus [constructor]: "options" parameter must be an object');
}
else {
options = options || {};
}
// Set the animation type
if (options.type && allowedTypes.indexOf(options.type) === -1) {
throw new Error('Vivus [constructor]: ' + options.type + ' is not an existing animation `type`');
}
else {
this.type = options.type || allowedTypes[0];
}
// Set the start type
if (options.start && allowedStarts.indexOf(options.start) === -1) {
throw new Error('Vivus [constructor]: ' + options.start + ' is not an existing `start` option');
}
else {
this.start = options.start || allowedStarts[0];
}
this.isIE = (navigator.userAgent.indexOf('MSIE') !== -1);
this.duration = parsePositiveInt(options.duration, 120);
this.delay = parsePositiveInt(options.delay, null);
this.dashGap = parsePositiveInt(options.dashGap, 2);
this.forceRender = options.hasOwnProperty('forceRender') ? !!options.forceRender : this.isIE;
this.selfDestroy = !!options.selfDestroy;
if (this.delay >= this.duration) {
throw new Error('Vivus [constructor]: delay must be shorter than duration');
}
};
/**
* Set up callback to the instance
* The method will not return enything, but will throw an
* error if the parameter is invalid
*
* @param {Function} callback Callback for the animation end
*/
Vivus.prototype.setCallback = function (callback) {
// Basic check
// if (!!callback && callback.constructor !== Function) {
if (!!callback && typeof callback !== 'function') {
throw new Error('Vivus [constructor]: "callback" parameter must be a function');
}
this.callback = callback || function () {};
};
/**
* Core
**************************************
*/
/**
* Map the svg, path by path.
* The method return nothing, it just fill the
* `map` array. Each item in this array represent
* a path element from the SVG, with informations for
* the animation.
*
* ```
* [
* {
* el: <DOMobj> the path element
* length: <number> length of the path line
* startAt: <number> time start of the path animation (in frames)
* duration: <number> path animation duration (in frames)
* },
* ...
* ]
* ```
*
*/
Vivus.prototype.mapping = function () {
var i, paths, path, pAttrs, pathObj, totalLength, lengthMeter, timePoint;
timePoint = totalLength = lengthMeter = 0;
paths = this.el.querySelectorAll('path');
for (i = 0; i < paths.length; i++) {
path = paths[i];
pathObj = {
el: path,
length: Math.ceil(path.getTotalLength())
};
// Test if the path length is correct
if (isNaN(pathObj.length)) {
if (window.console && console.warn) {
console.warn('Vivus [mapping]: cannot retrieve a path element length', path);
}
continue;
}
totalLength += pathObj.length;
this.map.push(pathObj);
path.style.strokeDasharray = pathObj.length + ' ' + (pathObj.length + this.dashGap);
path.style.strokeDashoffset = pathObj.length;
// Fix IE glitch
if (this.isIE) {
pathObj.length += this.dashGap;
}
this.renderPath(i);
}
totalLength = totalLength === 0 ? 1 : totalLength;
this.delay = this.delay === null ? this.duration / 3 : this.delay;
this.delayUnit = this.delay / (paths.length > 1 ? paths.length - 1 : 1);
for (i = 0; i < this.map.length; i++) {
pathObj = this.map[i];
switch (this.type) {
case 'delayed':
pathObj.startAt = this.delayUnit * i;
pathObj.duration = this.duration - this.delay;
break;
case 'oneByOne':
pathObj.startAt = lengthMeter / totalLength * this.duration;
pathObj.duration = pathObj.length / totalLength * this.duration;
break;
case 'async':
pathObj.startAt = 0;
pathObj.duration = this.duration;
break;
case 'scenario-sync':
path = paths[i];
pAttrs = this.parseAttr(path);
pathObj.startAt = timePoint + (parsePositiveInt(pAttrs['data-delay'], this.delayUnit) || 0);
pathObj.duration = parsePositiveInt(pAttrs['data-duration'], this.duration);
timePoint = pAttrs['data-async'] !== undefined ? pathObj.startAt : pathObj.startAt + pathObj.duration;
this.frameLength = Math.max(this.frameLength, (pathObj.startAt + pathObj.duration));
break;
case 'scenario':
path = paths[i];
pAttrs = this.parseAttr(path);
pathObj.startAt = parsePositiveInt(pAttrs['data-start'], this.delayUnit) || 0;
pathObj.duration = parsePositiveInt(pAttrs['data-duration'], this.duration);
this.frameLength = Math.max(this.frameLength, (pathObj.startAt + pathObj.duration));
break;
}
lengthMeter += pathObj.length;
this.frameLength = this.frameLength || this.duration;
}
};
/**
* Interval method to draw the SVG from current
* position of the animation. It update the value of
* `currentFrame` and re-trace the SVG.
*
* It use this.handle to store the requestAnimationFrame
* and clear it one the animation is stopped. So this
* attribute can be used to know if the animation is
* playing.
*
* Once the animation at the end, this method will
* trigger the Vivus callback.
*
*/
Vivus.prototype.drawer = function () {
var self = this;
this.currentFrame += this.speed;
if (this.currentFrame <= 0) {
this.stop();
this.reset();
} else if (this.currentFrame >= this.frameLength) {
this.stop();
this.currentFrame = this.frameLength;
this.trace();
if (this.selfDestroy) {
this.destroy();
}
this.callback(this);
} else {
this.trace();
this.handle = requestAnimFrame(function () {
self.drawer();
});
}
};
/**
* Draw the SVG at the current instant from the
* `currentFrame` value. Here is where most of the magic is.
* The trick is to use the `strokeDashoffset` style property.
*
* For optimisation reasons, a new property called `progress`
* is added in each item of `map`. This one contain the current
* progress of the path element. Only if the new value is different
* the new value will be applied to the DOM element. This
* method save a lot of resources to re-render the SVG. And could
* be improved if the animation couldn't be played forward.
*
*/
Vivus.prototype.trace = function () {
var i, progress, path;
for (i = 0; i < this.map.length; i++) {
path = this.map[i];
progress = (this.currentFrame - path.startAt) / path.duration;
progress = Math.max(0, Math.min(1, progress));
if (path.progress !== progress) {
path.progress = progress;
path.el.style.strokeDashoffset = Math.floor(path.length * (1 - progress));
this.renderPath(i);
}
}
};
/**
* Method forcing the browser to re-render a path element
* from it's index in the map. Depending on the `forceRender`
* value.
* The trick is to replace the path element by it's clone.
* This practice is not recommended because it's asking more
* ressources, too much DOM manupulation..
* but it's the only way to let the magic happen on IE.
* By default, this fallback is only applied on IE.
*
* @param {Number} index Path index
*/
Vivus.prototype.renderPath = function (index) {
if (this.forceRender && this.map && this.map[index]) {
var pathObj = this.map[index],
newPath = pathObj.el.cloneNode(true);
pathObj.el.parentNode.replaceChild(newPath, pathObj.el);
pathObj.el = newPath;
}
};
/**
* Trigger to start of the animation.
* Depending on the `start` value, a different script
* will be applied.
*
* If the `start` value is not valid, an error will be thrown.
* Even if technically, this is impossible.
*
*/
Vivus.prototype.starter = function () {
switch (this.start) {
case 'manual':
return;
case 'autostart':
this.play();
break;
case 'inViewport':
var self = this,
listener = function () {
if (self.isInViewport(self.el, 1)) {
self.play();
window.removeEventListener('scroll', listener);
}
};
window.addEventListener('scroll', listener);
listener();
break;
}
};
/**
* Controls
**************************************
*/
/**
* Reset the instance to the initial state : undraw
* Be careful, it just reset the animation, if you're
* playing the animation, this won't stop it. But just
* make it start from start.
*
*/
Vivus.prototype.reset = function () {
this.currentFrame = 0;
this.trace();
return this;
};
/**
* Play the animation at the desired speed.
* Speed must be a valid number (no zero).
* By default, the speed value is 1.
* But a negative value is accepted to go forward.
*
* And works with float too.
* But don't forget we are in JavaScript, se be nice
* with him and give him a 1/2^x value.
*
* @param {number} speed Animation speed [optional]
*/
Vivus.prototype.play = function (speed) {
if (speed && typeof speed !== 'number') {
throw new Error('Vivus [play]: invalid speed');
}
this.speed = speed || 1;
if (!this.handle) {
this.drawer();
}
return this;
};
/**
* Stop the current animation, if on progress.
* Should not trigger any error.
*
*/
Vivus.prototype.stop = function () {
if (this.handle) {
cancelAnimFrame(this.handle);
delete this.handle;
}
return this;
};
/**
* Destroy the instance.
* Remove all bad styling attributes on all
* path tags
*
*/
Vivus.prototype.destroy = function () {
var i, path;
for (i = 0; i < this.map.length; i++) {
path = this.map[i];
path.el.style.strokeDashoffset = null;
path.el.style.strokeDasharray = null;
this.renderPath(i);
}
};
/**
* Utils methods
* from Codrops
**************************************
*/
/**
* Parse attributes of a DOM element to
* get an object of {attributeName => attributeValue}
*
* @param {object} element DOM element to parse
* @return {object} Object of attributes
*/
Vivus.prototype.parseAttr = function (element) {
var attr, output = {};
if (element && element.attributes) {
for (var i = 0; i < element.attributes.length; i++) {
attr = element.attributes[i];
output[attr.name] = attr.value;
}
}
return output;
};
/**
* Reply if an element is in the page viewport
*
* @param {object} el Element to observe
* @param {number} h Percentage of height
* @return {boolean}
*/
Vivus.prototype.isInViewport = function (el, h) {
var scrolled = this.scrollY(),
viewed = scrolled + this.getViewportH(),
elBCR = el.getBoundingClientRect(),
elHeight = elBCR.height,
elTop = scrolled + elBCR.top,
elBottom = elTop + elHeight;
// if 0, the element is considered in the viewport as soon as it enters.
// if 1, the element is considered in the viewport only when it's fully inside
// value in percentage (1 >= h >= 0)
h = h || 0;
return (elTop + elHeight * h) <= viewed && (elBottom) >= scrolled;
};
/**
* Alias for document element
*
* @type {DOMelement}
*/
Vivus.prototype.docElem = window.document.documentElement;
/**
* Get the viewport height in pixels
*
* @return {integer} Viewport height
*/
Vivus.prototype.getViewportH = function () {
var client = this.docElem.clientHeight,
inner = window.innerHeight;
if (client < inner) {
return inner;
}
else {
return client;
}
};
/**
* Get the page Y offset
*
* @return {integer} Page Y offset
*/
Vivus.prototype.scrollY = function () {
return window.pageYOffset || this.docElem.scrollTop;
};
/**
* Alias for `requestAnimationFrame` or
* `setTimeout` function for deprecated browsers.
*
*/
requestAnimFrame = (function () {
return (
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback){
return window.setTimeout(callback, 1000 / 60);
}
);
})();
/**
* Alias for `cancelAnimationFrame` or
* `cancelTimeout` function for deprecated browsers.
*
*/
cancelAnimFrame = (function () {
return (
window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
window.oCancelAnimationFrame ||
window.msCancelAnimationFrame ||
function(id){
return window.clearTimeout(id);
}
);
})();
/**
* Parse string to integer.
* If the number is not positive or null
* the method will return the default value
* or 0 if undefined
*
* @param {string} value String to parse
* @param {*} defaultValue Value to return if the result parsed is invalid
* @return {number}
*
*/
parsePositiveInt = function (value, defaultValue) {
var output = parseInt(value, 10);
return (output >= 0) ? output : defaultValue;
};
window.Vivus = Vivus;
}());