-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathelement.js
More file actions
2730 lines (2457 loc) · 88.3 KB
/
element.js
File metadata and controls
2730 lines (2457 loc) · 88.3 KB
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
var utils = require('../utils.js'),
global_opts = require('../global_opts.js');
var iter = utils.iter,
is = utils.is;
var engine = require('engine');
var C = require('../constants.js');
var events = require('../events.js'),
provideEvents = events.provideEvents,
EventState = events.EventState;
var Transform = require('../../vendor/transform.js');
var Render = require('../render.js');
var Brush = require('../graphics/brush.js'),
Color = require('../graphics/color.js'),
Bounds = require('../graphics/bounds.js');
var Timeline = require('./timeline.js');
var Modifier = require('./modifier.js'),
Painter = require('./painter.js');
var errors = require('../errors.js'),
ErrLoc = require('../loc.js').Errors;
// Internal Constants
// -----------------------------------------------------------------------------
var TIME_PRECISION = 9; // the number of digits after the floating point
// to round the time when comparing with bands and so on;
// used to get rid of floating point-conversion issues
function t_adjust(t) {
return utils.roundTo(t, TIME_PRECISION);
}
function t_cmp(t0, t1) {
if (t_adjust(t0) > t_adjust(t1)) return 1;
if (t_adjust(t0) < t_adjust(t1)) return -1;
return 0;
}
Element.DEFAULT_PVT = [ 0.5, 0.5 ];
Element.DEFAULT_REG = [ 0.0, 0.0 ];
/**
* @class anm.Element
*
* An Element is literally everything what may be drawn in your animation. Or even not
* to be drawn, but to have some position. Or to have children elements. Or both.
*
* There are also some setter-like methods, and if a name of some setter matches
* to the according property it sets, a `$` symbol is appended to a property name: like
* the method {@link anm.Element#fill .fill} and the property {@link anm.Element#$fill .$fill}. This way allows us not only
* to avoid name-clashed, but also serves as an additional mark for user that a value of this
* property is easier to construct with a corresponding helper method, rather than,
* for example, creating a special {@link anm.Brush Brush} object for a `fill`.
*
* See {@link anm.Element#add add} and {@link anm.Element#remove remove} methods for documentation
* on adding and removing children elements.
*
* See {@link anm.Element#each each} and {@link anm.Element#traverse traverse} method for documentation
* on iteration over children elements.
*
* See {@link anm.Element#path path}, {@link anm.Element#text text} and {@link anm.Element#image image}
* for documentation on changing the type of the element and the way it draws itself.
*
* See {@link anm.Element#rect rect}, {@link anm.Element#oval oval} and other shape-related methods
* for documentation on changing element's shape.
*
* See {@link anm.Element#fill fill}, {@link anm.Element#stroke stroke} and
* {@link anm.Element#shadow shadow} methods for documentation on changing appearance of the element.
* (Fill/Shadow only apply if element is `path`, `shape` or `text`).
*
* See {@link anm.Element#band band} for documentation on how to set element's lifetime relatively to its parent.
*
* See {@link anm.Element#repeat repeat}, {@link anm.Element#once once}, {@link anm.Element#stay stay},
* {@link anm.Element#loop loop}, {@link anm.Element#bounce bounce} for documentation on how to make this element
* self-repeat or to stay in its last state inside the parent's lifetime.
*
* See {@link anm.Tween Tween} and {@link anm.Element#tween tween} method for documentation on adding tweens.
*
* See {@link anm.Modifier Modifier} in pair with {@link anm.Element#modify modify} method and {@link anm.Painter Painter}
* in pair with {@link anm.Element#modify paint} method for documentation on
* a custom drawing or positioning the element in time.
*
* @constructor
*
* @param {String} [name]
* @param {Function} [draw] If one function may draw this element, you may provide it here
* @param {anm.Element} draw.this
* @param {Context2D} draw.ctx
* @param {Function} [onframe] This function may be called on every frame and modify this element position
* @param {anm.Element} onframe.this
* @param {Number} onframe.time A current local time
*/
function Element(name, draw, onframe) {
this.id = utils.guid(); /** @property {String} id element internal ID @readonly */
this.name = name || ''; /** @property {String} name element's name, if specified */
this.type = C.ET_EMPTY; /** @property {anm.C.ET_*} type of the element: `ET_EMPTY` (default), `ET_PATH`, `ET_TEXT` or `ET_SHEET` @readonly */
this.children = []; /** @property {Array[anm.Element]} children A list of children elements for this one. Use `.add()` and `.remove()` methods to change @readonly */
this.parent = null; /** @property {anm.Element} parent parent element, if exists @readonly */
this.level = 0; /** @property {Number} level how deep this element is located in animation tree @readonly */
this.anim = null; /** @property {anm.Animation} anim the animation this element belongs to / registered in, if it really belongs to one @readonly */
this.scene = null; /** @property {anm.Scene} scene the scene this element belongs to / registered in, if it really belongs to one @readonly */
this.active = true; /** @property {Boolean} active Is this element active or not (internal flag to control if this element is "alive") @readonly */
this.disabled = false; /** @property {Boolean} disabled Is this element disabled or not (if disabled—not transformed and not drawn) */
this.visible = true; /** @property {Boolean} visible Is this element visible or not (if not—transformed, but not drawn) */
this.isMask = false; /** @property {Boolean} isMask Is this element a mask, or not (if yes—transformed, but not drawn) */
this.affectsChildren = true; /** @property {Boolean} affectsChildren Is this element local time affects children local time */
this.$data = null; /** @property {Any} $data user data */
this.registered = false; // is registered in animation or not
this.rendering = false; // in process of rendering or not
this.initState(); // initializes matrix, values for transformations
this.initVisuals(); // initializes visual representation storage and data
this.initTime(); // initialize time position and everything related to time jumps
this.initEvents(); // initialize events storage and mechanics
this.$modifiers = {}; /** @property {Array[anm.Modifier]} $modifiers A list of modifiers, grouped by type @readonly */
this.$painters = {}; /** @property {Array[anm.Painter]} $painters A list of painters, grouped by type @readonly */
if (onframe) this.modify(onframe);
if (draw) this.paint(draw);
this.__modifying = null; // current modifiers class, if modifying
this.__painting = null; // current painters class, if painting
this.__modifiers_hash = {}; // applied modifiers, by id
this.__painters_hash = {}; // applied painters, by id
this.__detachQueue = [];
// FIXME: add all of the `provideEvents` method to docs for all elements who provide them
var me = this,
default_on = this.on;
/**
* @method on
*
* Subscribe for an element-related event with a handler.
*
* There's quite big list of possible events to subscribe, and it will be added here later. `TODO`
*
* @param {C.X*} type event type
* @param {Function} handler event handler
*/
this.on = function(type, handler) {
/* if (events.mouseOrKeyboard(type)) {
return this.m_on.call(me, type, handler);
} else */ return default_on.call(me, type, handler);
// return this; // FIXME: make chainable
};
this.addSysModifiers();
this.addSysPainters();
if (global_opts.liveDebug) this.addDebugRender();
}
Element._$ = function(name, draw, onframe) { return new Element(name, draw, onframe); };
Element.NO_BAND = null;
Element.DEFAULT_LEN = Infinity;
Element._customImporters = [];
provideEvents(Element, [ C.X_MCLICK, C.X_MDCLICK, C.X_MUP, C.X_MDOWN,
C.X_MMOVE, C.X_MOVER, C.X_MOUT ]);
/**
* @method is
*
* Check, if this element represents {@link anm.Path Path}, {@link anm.Text Text},
* {@link anm.Sheet Sheet}, or it's empty
*
* @param {String} type to check for: `'empty'`, `'path'`, `'text'`, `'image'`, `'audio'`, `'video'`...
* @return {Boolean}
*/
Element.prototype.is = function(type) {
return this.type == type;
};
Element.prototype.initState = function() {
/** @property {Number} x position on the X axis, relatively to parent */
/** @property {Number} y position on the Y axis, relatively to parent */
/** @property {Number} angle rotation angle, in radians, relative to parent */
/** @property {Number} sx scale over X axis, relatively to parent */
/** @property {Number} sy scale over Y axis, relatively to parent */
/** @property {Number} hx skew over X axis, relatively to parent */
/** @property {Number} hy skew over Y axis, relatively to parent */
/** @property {Number} alpha opacity, relative to parent */
// current state
this.x = 0; this.y = 0; // dynamic position
this.sx = 1; this.sy = 1; // scale by x / by y
this.hx = 0; this.hy = 0; // shear by x / by y
this.angle = 0; // rotation angle
this.alpha = 1; // opacity
// these values are for user to set
//this.dt = null;
//this.t = null; this.rt = null; this.key = null;
// cur local time (t) or 0..1 time (rt) or by key (t have highest priority),
// if both are null — stays as defined
if (this.matrix) { this.matrix.reset(); }
else { this.matrix = new Transform(); }
// previous state
// FIXME: get rid of previous state completely?
// of course current state should contain previous values before executing
// modifiers on current frame, but they may happen to be overwritten by other modifiers,
// so sometimes it'd be nice to know what was there at previous time for sure;
// though user may modify time value also through this.t, and it should contain
// current time (probably), but not the last one.
// pros: it is useful for collisions, and user can't store it himself
// because modifiers modify the state in their order and there will be
// no exact moment when it is 'previous', since there always will be
// some system modifiers which will work before the user's ones
// (or it's ok?)
// cons: it's unreadable and may confuse users (with what?)
this._x = 0; this._y = 0; // dynamic position
this._sx = 1; this._sy = 1; // scale by x / by y
this._hx = 1; this._hy = 1; // shear by x / by y
this._angle = 0; // rotation angle
this._alpha = 1; // opacity
// these values are set by engine to provide user with information
// when previous state was rendered
//this._dt = null;
//this._t = null; this._rt = null; this._key = null;
// cur local time (t) and 0..1 time (rt) and,
// if it was ever applied, the last applied key
if (this._matrix) { this._matrix.reset(); }
else { this._matrix = new Transform(); }
/** @property {Array[Number]} $reg registration point (X and Y position) @readonly */
/** @property {Array[Number]} $pivot pivot point (relative X and Y position) @readonly */
this.$reg = Element.DEFAULT_REG; // registration point (static values)
this.$pivot = Element.DEFAULT_PVT; // pivot (relative to dimensions)
return this;
};
Element.prototype.resetState = Element.prototype.initState;
Element.prototype.initVisuals = function() {
// since properties below will conflict with getters/setters having same names,
// they're renamed with dollar-sign. this way also allows methods to be replaced
// with native JS 1.5 getters/setters just in few steps. (TODO)
/** @property {anm.Brush} $fill element fill @readonly */
/** @property {anm.Brush} $stroke element stroke @readonly */
/** @property {anm.Brush} $shadow element shadow @readonly */
this.$fill = null; // Fill instance
this.$stroke = null; // Stroke instance
this.$shadow = null; // Shadow instance
// TODO: change to `{anm.Path|anm.Sheet|anm.Text} $visual`
/** @property {anm.Path} $path set to some curve, if it's a shape @readonly */
/** @property {anm.Sheet} $sheet set to some image, if it's an image @readonly */
/** @property {anm.Text} $text set to some text, if it's a text @readonly */
this.$path = null; // Path instanse, if it is a shape
this.$text = null; // Text data, if it is a text
this.$image = null; // Sheet instance, if it is an image or a sprite sheet
this.composite_op = null; // composition operation
/** @property {anm.Element} $mask masking element @readonly */
this.$mask = null; // Element instance, if this element has a mask
this.$mpath = null; // move path, though it's not completely "visual"
this.$bounds = null; // Element bounds incl. children, cached by time position
this.lastBoundsSavedAt = null; // time, when bounds were saved last time
this.$my_bounds = null; // Element bounds on its own, cached
this.$audio = null;
this.$video = null;
return this;
};
Element.prototype.resetVisuals = Element.prototype.initVisuals;
Element.prototype.initTime = function() {
/** @property {anm.Timeline} timeline instance @readonly */
this.timeline = new Timeline(this);
/** @property {String} switch (name of the child to render in current moment) */
this.switch = null;
return this;
};
Element.prototype.resetTime = function() {
this.timeline.reset();
this.switch = null;
};
Element.prototype.initEvents = function() {
this.evts = {}; // events cache
this.__evt_st = new EventState(); // event state
this.__evtCache = [];
return this;
};
Element.prototype.resetEvents = Element.prototype.initEvents;
/**
* @method path
* @chainable
*
* Set this element to be a {@link anm.Path Path} or get current path.
*
* Examples:
*
* * `elm.path("M0.0 10.0 L20.0 20.0 C10.0 20.0 15.0 30.0 10.0 9.0 Z")`
* * `elm.path(new Path().move(0, 10).curve(10, 20, 15, 30, 10, 9))`
* * `var my_path = elm.path()`
*
* @param {String|anm.Path} [path]
* @return {anm.Path|anm.Element}
*/
Element.prototype.path = function(value) {
if (value) {
this.invalidate();
this.type = C.ET_PATH;
this.$path = is.str(value) ? new Path(value) : value;
return this;
} else return this.$path;
};
/**
* @method text
* @chainable
*
* Set this element to be a {@link anm.Text Text} or get current text.
*
* Examples:
*
* * `elm.text("my text")`
* * `elm.text(["text","in three","lines"])`
* * `elm.text(new Text("My Text").font("Arial"))`
* * `elm.text(new Text(["Two lines", "of text"]).font("italic 20px Arial").align(anm.C.TA_RIGHT))`
* * `var my_text = elm.text()`
*
* @param {String|[String]|anm.Text} [text]
* @return {anm.Text|anm.Element}
*/
Element.prototype.text = function(value) {
if (value) {
this.invalidate();
this.type = C.ET_TEXT;
this.$text = (is.str(value) || is.arr(value)) ? new Text(value) : value;
return this;
} else return this.$text;
};
/**
* @method image
* @chainable
*
* Set this element to be an {@link anm.Sheet Image/Sheet} or get current image.
*
* Examples:
*
* * `elm.image("path://to.my_image.jpg")`
* * `elm.image(new Image("path://to.my_image.jpg"))`
* * `elm.image(new Image("path://to.my_image.jpg", function() { console.log("image received"); }))`
* * `var my_image = elm.image()`
*
* @param {String|anm.Image|anm.Sheet} [image] URL or anm.Image instance
* @param {Function} [callback] a function to be called when image will be received (NB: only appliable if `image` parameter is specified as an URL string)
* @param {anm.Image} [callback.image] anm.Image instance
* @param {DomElement} [callback.element] Image Element
* @return {anm.Image|anm.Sheet|anm.Element}
*/
// TODO: add spite-sheet methods and documenation
Element.prototype.image = function(value, callback) {
if (value) {
this.invalidate();
this.type = C.ET_SHEET;
this.$image = (is.str(value)) ? new Image(value, callback) : value;
return this;
} else return this.$image;
};
/**
* @method fill
* @chainable
*
* Set fill for this element
*
* Examples:
*
* * `elm.fill("#ffaa0b")`
* * `elm.fill("rgb(255,170,11)")`
* * `elm.fill("rgb(255,170,11,0.8)")`
* * `elm.fill("hsl(120,50,100%)")`
* * `elm.fill("hsla(120,50,100%,0.8)")`
* * `elm.fill(anm.Color.rgb(1.0,0.6,0.1))`
* * `elm.fill(anm.Color.hsla(Math.PI/3,50,1.0))`
* * `elm.fill(anm.Brush.gradient().stops({0: "#000", 0.5: "#ccc"}))`
* * `var brush = elm.fill()`
*
* @param {String|anm.Brush} [color]
* @return {anm.Brush|anm.Element}
*/
Element.prototype.fill = function(value) {
if (value) {
this.$fill = (value instanceof Brush) ? value : Brush.fill(value);
return this;
} else return this.$fill;
};
/**
* @method noFill
* @chainable
*
* Remove fill from this element (set it to transparency)
*
* @return {anm.Element}
*/
Element.prototype.noFill = function() {
this.$fill = Color.TRANSPARENT;
return this;
};
/**
* @method stroke
* @chainable
*
* Set stroke for this element
*
* Examples:
*
* * `elm.stroke("#ffaa0b", 2)`
* * `elm.stroke("rgb(255,170,11)", 4)`
* * `elm.stroke("rgb(255,170,11,0.8)", 5)`
* * `elm.stroke("hsl(120,50,100%)", 3)`
* * `elm.stroke("hsla(120,50,100%,0.8)", 1)`
* * `elm.stroke(anm.Color.rgb(1.0,0.6,0.1), 2)`
* * `elm.stroke(anm.Color.hsla(Math.PI/3,50,1.0), 5)`
* * `elm.stroke(anm.Brush.gradient().stops({0: "#000", 0.5: "#ccc"}), 10)`
* * `var brush = elm.stroke()`
*
* @param {String|anm.Brush} [color] color of the stroke
* @param {Number} [width] width of the stroke
* @return {anm.Brush|anm.Element}
*/
Element.prototype.stroke = function(value, width) {
if (value) {
if (value instanceof Brush) {
this.$stroke = value;
if (is.defined(width)) this.$stroke.width = width;
} else {
this.$stroke = Brush.stroke(value, width);
}
return this;
} else return this.$stroke;
};
/**
* @method noStroke
* @chainable
*
* Remove stroke from this element
*
* @return {anm.Element}
*/
Element.prototype.noStroke = function() {
this.$stroke = null;
return this;
};
/**
* @method shadow
* @chainable
*
* Set shadow for this element
*
* Examples:
* * `elm.shadow("#ffaa0b", 3)`
* * `elm.shadow("rgb(255,170,11)", 3, 5, 5)`
* * `var brush = elm.shadow()`
*
* @param {String|anm.Brush} [color] color of the shadow
* @param {Number} [radius] radius of the shadow
* @param {Number} [x] x offset of the shadow
* @param {Number} [y] y offset of the shadow
* @return {anm.Brush|anm.Element}
*/
Element.prototype.shadow = function(value, radius, x, y) {
if (value) {
if (value instanceof Brush) {
this.$shadow = value;
} else {
this.$shadow = Brush.shadow(value, radius, x, y);
}
return this;
} else return this.$shadow;
};
/**
* @private @method modifiers
*
* Call all modifiers of the element. Used in element rendering process.
* See {@link anm.Modifier Modifier} for detailed documenation on modifiers.
*
* @param {Number} ltime local time of the element (relatively to parent element), in seconds
* @param {Number} [dt] time passed since last frame was rendered, in seconds
* @param {[C.MOD_*]} [types] the types and order of modifiers to call (`SYSTEM`, `TWEEN`, `USER`, `EVENT`)
*
* @return [Boolean] `true` if this element shoud be rendered, `false` if not
*/
Element.prototype.modifiers = function(ltime, dt, types) {
var elm = this;
var order = types || Modifier.ALL_MODIFIERS;
dt = dt || 0;
// copy current state as previous one
elm.applyPrevState(elm);
elm.__loadEvents();
var modifiers = this.$modifiers;
var type, typed_modifiers, modifier, lbtime;
for (var i = 0, il = order.length; i < il; i++) { // for each type
type = order[i];
elm.__modifying = type;
elm.__mbefore(type);
typed_modifiers = modifiers[type];
if (typed_modifiers) {
for (var j = 0, jl = typed_modifiers.length; j < jl; j++) {
modifier = typed_modifiers[j];
// lbtime is band-apadted time, if modifier has its own band
lbtime = elm.__adaptModTime(modifier, ltime);
// `null` will be returned from `__adaptModTime` for some modifier,
// if it is required to skip current one, but continue calling others;
// when `false` is returned for some modifier, this element should not be rendered at all
if (lbtime === null) continue;
// modifier will return false if it is required to skip all next modifiers,
// returning false from our function means the same
// // time, dt, duration
if ((lbtime === false) || (modifier.apply(elm, lbtime[0], dt, lbtime[1]) === false)) {
elm.__mafter(ltime, elm.__modifying, false);
elm.__modifying = null;
return false; // exit the method
}
}
}
elm.__mafter(ltime, type, true);
} // for each type
elm.matrix = Element.getMatrixOf(elm, elm.matrix);
elm.__modifying = null;
elm.__appliedAt = ltime;
elm.resetEvents();
return true;
};
/**
* @private @method painters
*
* Call all painters of the element. Used in element rendering process.
* See {@link anm.Painter Painter} for detailed documenation on painters.
*
* @param {Context2D} ctx 2D context where element should be drawn
* @param {[C.PNT_*]} [types] the types and order of painters to call (`SYSTEM`, `USER`, `DEBUG`)
*/
Element.prototype.painters = function(ctx, types) {
var elm = this;
var order = types || Painter.ALL_PAINTERS;
var painters = this.$painters;
var type, typed_painters, painter;
for (var i = 0, il = order.length; i < il; i++) { // for each type
type = order[i];
elm.__painting = type;
elm.__pbefore(ctx, type);
typed_painters = painters[type];
if (typed_painters) {
for (var j = 0, jl = typed_painters.length; j < jl; j++) {
painter = typed_painters[j];
painter.apply(elm, ctx);
}
}
elm.__pafter(ctx, type);
} // for each type
elm.__painting = null;
};
/**
* @private @method forAllModifiers
*
* Iterate over all of the modifiers and call given function
*
* @param {Function} fn function to call
* @param {anm.Modifier} fn.modifier modifier
* @param {C.MOD_*} fn.type modifier type
*/
Element.prototype.forAllModifiers = function(f) {
var order = Modifier.ALL_MODIFIERS;
var modifiers = this.$modifiers;
var type, typed_modifiers, modifier;
for (var i = 0, il = order.length; i < il; i++) { // for each type
type = order[i];
typed_modifiers = modifiers[type];
if (typed_modifiers) {
for (var j = 0, jl = typed_modifiers.length; j < jl; j++) {
f(typed_modifiers[j], type);
}
}
}
};
/**
* @private @method forAllPainters
*
* Iterate over all of the painters and call given function
*
* @param {Function} fn function to call
* @param {anm.Painter} fn.painter painter
* @param {C.PNT_*} fn.type painter type
*/
Element.prototype.forAllPainters = function(f) {
var order = Painter.ALL_PAINTERS;
var painters = this.$painters;
var type, typed_painters, painter;
for (var i = 0, il = order.length; i < il; i++) { // for each type
type = order[i];
typed_painters = painters[type];
if (typed_painters) {
for (var j = 0, jl = typed_painters.length; j < jl; j++) {
f(typed_painters[j], type);
}
}
}
};
/**
* @method draw
*
* Draw element over some context, without applying transformations, even if element
* has some, since they depend on time. To draw element along with applying
* transformations in one call, use {@link anm.Element#render render} method.
*
* @param {Context2D} ctx context, where element should be drawn
*/
// > Element.draw % (ctx: Context)
Element.prototype.draw = Element.prototype.painters;
/**
* @private @method transform
*
* Apply every transformation in current matrix to context.
*
* @param {Context2D} ctx context
*/
Element.prototype.transform = function(ctx) {
ctx.globalAlpha *= this.alpha;
this.matrix.apply(ctx);
return this.matrix;
};
/**
* @private @method invTransform
*
* Invert current matrix and apply every transformation in it to context.
*
* @param {Context2D} ctx context
*/
Element.prototype.invTransform = function(ctx) {
var inv_matrix = Element.getIMatrixOf(this); // this will not write to elm matrix
ctx.globalAlpha *= this.alpha;
inv_matrix.apply(ctx);
return inv_matrix;
};
Element.prototype.tick = function(dt) {
if (this.disabled) return;
// TODO: check switcher
var resultTime;
if (!this.parent && this.scene && this.scene.affectsChildren) {
resultTime = this.timeline.tickRelative(this.scene.timeline, dt);
} else if (this.parent && this.parent.affectsChildren) {
resultTime = this.timeline.tickRelative(this.parent.timeline, dt);
} else {
resultTime = this.timeline.tick(dt);
}
var isActive = this.timeline.isActive() && this.modifiers(resultTime, dt);
if (isActive) {
this.each(function(child) {
child.tick(dt);
});
}
this.active = isActive;
return resultTime;
};
Element.prototype._checkSwitcher = function(next) {
var parent = this.parent;
if (!parent || !parent.switch) return next;
if (parent.switch === C.SWITCH_OFF) return NO_TIME;
if ((parent.switch === this.name) && parent.switch_band) {
if (next === NO_TIME) return NO_TIME;
return next - parent.switch_band[0];
} else return NO_TIME;
};
/**
* @method render
* @chainable
*
* Render this element at a given global time, which means execute its full render
* cycle, starting with checking its time band, and, if band matches time and this
* element is enabled, calling _modifiers_ (tweens), applying its state to context
* and then drawing it with _painters_. Plus, does the same recursively for every
* child or sub-child, if has some.
*
* @param {Context2D} ctx context to draw onto
* @param {Number} dt time passed since the previous frame was rendered, in seconds
*
* @return {anm.Element} itself
*/
// > Element.render % (ctx: Context, gtime: Float, dt: Float)
Element.prototype.render = function(ctx) {
if (this.disabled || !this.active) return;
this.rendering = true;
if (this.visible) {
if (!this.isMask && !this.$mask) {
ctx.save();
this.transform(ctx);
this.painters(ctx);
this.each(function(child) {
child.render(ctx);
});
ctx.restore();
} else if (this.isMask) { // this element is a mask
this._renderAsMask();
} else if (this.$mask) { // this element is masked
ctx.save();
this._renderAsMasked(ctx);
ctx.restore();
}
}
this.__postRender();
this.rendering = false;
return this;
};
Element.prototype._renderAsMask = function() {
this.ensureHasMaskCanvas();
var mcvs = this.__maskCvs,
mctx = this.__maskCtx,
bcvs = this.__backCvs;
// FIXME: test if bounds are not empty
var bounds_pts = this.bounds().toPoints();
var minX = Number.MAX_VALUE, minY = Number.MAX_VALUE,
maxX = Number.MIN_VALUE, maxY = Number.MIN_VALUE;
var pt;
for (var i = 0, il = bounds_pts.length; i < il; i++) {
pt = bounds_pts[i];
if (pt.x < minX) minX = pt.x;
if (pt.y < minY) minY = pt.y;
if (pt.x > maxX) maxX = pt.x;
if (pt.y > maxY) maxY = pt.y;
}
var ratio = engine.PX_RATIO,
x = minX, y = minY,
width = Math.round(maxX - minX),
height = Math.round(maxY - minY);
var last_cvs_size = this._maskCvsSize || engine.getCanvasSize(mcvs);
var scale = ratio; // multiple by global scale when it's known
if ((last_cvs_size[0] < width) ||
(last_cvs_size[1] < height)) {
// mcvs/bcvs both always have the same size, so we save/check only one of them
this._maskCvsSize = engine.setCanvasSize(mcvs, width, height);
engine.setCanvasSize(bcvs, width, height);
} else {
this._maskCvsSize = last_cvs_size;
}
this._maskCvsPos = [ x, y ];
mctx.clearRect(0, 0, width*scale, height*scale);
mctx.save();
mctx.setTransform(scale, 0, 0, scale, -x*scale, -y*scale);
// FIXME: this should be performed one time for all masked elements!
this.transform(mctx);
this.painters(mctx);
this.each(function(child) {
child.render(mctx);
});
mctx.restore();
};
Element.prototype._renderAsMasked = function(ctx) {
// FIXME: the complete mask process should be a Painter.
var mask = this.$mask;
var ratio = engine.PX_RATIO;
if (!mask.__maskCvs) throw new Error('Mask canvas is not ready!');
var mcvs = mask.__maskCvs,
bcvs = mask.__backCvs,
bctx = mask.__backCtx;
var maskSize = mask._maskCvsSize,
maskPos = mask._maskCvsPos;
var width = maskSize[0],
height = maskSize[1],
x = maskPos[0], y = maskPos[1];
var scale = ratio; // multiple by global scale when it's known
bctx.clearRect(0, 0, width*scale, height*scale);
bctx.save();
bctx.setTransform(scale, 0, 0, scale, -x*scale, -y*scale);
this.transform(bctx);
this.painters(bctx);
this.each(function(child) {
child.render(bctx);
});
bctx.globalCompositeOperation = 'destination-in';
bctx.setTransform(1, 0, 0, 1, 0, 0);
bctx.drawImage(mcvs, 0, 0);
ctx.drawImage(bcvs,
0, 0, Math.floor(width * scale), Math.floor(height * scale),
x, y, width, height);
bctx.restore();
};
/**
* @method pivot
* @chainable
*
* Assign a pivot for this element (given in relative coords to element's bounds).
* This point becomes the center for all the applied transformations.
*
* @param {Number} x X position, in range 0..1
* @param {Number} y Y position, in range 0..1
* @return {anm.Element} itself
*/
Element.prototype.pivot = function(x, y) {
this.$pivot = [ x, y ];
return this;
};
/**
* @method reg
* @chainable
*
* Assign a registration point for this element (given in points).
* This point becomes the starting point for all the applied transformations.
*
* @param {Number} x X position, in points
* @param {Number} y Y position, in points
* @return {anm.Element} itself
*/
Element.prototype.reg = function(x, y) {
this.$reg = [ x, y ];
return this;
};
/**
* @method move
* @chainable
*
* Move this element to some point, once and forever.
*
* NB: If this element has tweens, event handlers and/or any modifiers in general,
* they will rewrite this value on the very next render call—so if you want, while having
* modifiers, to constantly add these values to the element position, it is
* recommended to better add a correspoding static tween or modifier to it,
* rather than calling this method.
*
* @param {Number} x X position, in points
* @param {Number} y Y position, in points
* @return {anm.Element} itself
*/
Element.prototype.move = function(x, y) {
this.x = x;
this.y = y;
return this;
};
/**
* @method rotate
* @chainable
*
* Rotate this element to some angle, once and forever.
*
* NB: If this element has tweens, event handlers and/or any modifiers in general,
* they will rewrite this value on the very next render call—so if you want, while having
* modifiers, to constantly add this value to the element rotation state, it is
* recommended to better add a correspoding static tween or modifier to it,
* rather than calling this method.
*
* @param {Number} angle angle, in radians
* @return {anm.Element} itself
*/
Element.prototype.rotate = function(angle) {
this.angle = angle;
return this;
};
/**
* @method rotateInDeg
* @chainable
*
* Rotate this element to some angle, once and forever.
*
* NB: If this element has tweens, event handlers and/or any modifiers in general,
* they will rewrite this value on the very next render call—so if you want, while having
* modifiers, to constantly add this value to the element rotation state, it is
* recommended to better add a correspoding static tween or modifier to it,
* rather than calling this method.
*
* @param {Number} angle angle, in degrees
* @return {anm.Element} itself
*/
Element.prototype.rotateInDeg = function(angle) {
return this.rotate(angle / 180 * Math.PI);
};
/**
* @method scale
* @chainable
*
* Scale this element, once and forever.
*
* NB: If this element has tweens, event handlers and/or any modifiers in general,
* they will rewrite this value on the very next render call—so if you want, while having
* modifiers, to constantly add these values to the element scale state, it is
* recommended to better add a correspoding static tween or modifier to it,
* rather than calling this method.
*
* @param {Number} sx scale by X axis, in points
* @param {Number} sy scale by Y axis, in points
* @return {anm.Element} itself
*/
Element.prototype.scale = function(sx, sy) {
this.sx = sx;
this.sy = sy;
return this;
};
/**
* @method skew