-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.ndg
993 lines (732 loc) · 32.4 KB
/
index.ndg
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
Unveil.js
================================================================================
**Unveil** is a data exploration and visualization toolkit that utilizes data-driven
software design.
It features generic data abstraction through Collections, a unified interface
for developing pluggable visualizations, and a Scenegraph implementation that
simplifies the usage of the the "HTML 5 Canvas API"[http://dev.w3.org/html5/canvas-api/canvas-2d-api.html].
Although shipping with it's own little graphic library, the *Scene API*, Unveil.js
is designed to be used with any other visualization library. So in the first
place, it suggests a different approach on how you deal with domain data in a
visualization scenario.
**Note:**
This documentation is generated on the fly using the "Ndogen"[http://github.com/oliver----/ndogen] documentation generator.
Since this instant doc-generation part is under heavy development, you'll
experience some glitches. We're working on it! Please have a look at the "raw markup"[http://github.com/michael/unveil/blob/master/index.ndg] too.
The data visualization process
================================================================================
When faced with a data visualization task you'll usually go through a workflow
that looks like this:
1. Data aggregation
--------------------------------------------------------------------------------
This includes querying and preparing data, which is not covered by Unveil.js.
However the outcome of this process should be a collection of data items
represented in a uniform Collection format (JSON), ideally served dynamically
through a webservice.
I've recently implemented such an aggregation service that uses data from
Freebase (in this example music artist data). Therefore I've used "Acre"[http://acre.freebase.com/]
,a hosted platform that allows you to build applications or services from Freebase
data.
"This simple Acre script"[http://acre.freebase.com/#!path=//collections.ma.user.dev/artists] queries
the Freebase.com graph for music artists of certain genres. It processes that data and translate
it into the Unveil.js Collection format. The result is a web service that turns freebase data
into a Collection on the fly. And here is the "result"[http://collections.freebaseapps.com/artists].
Btw: I just used Freebase Acre for the first time. It's simply perfect for on-the-fly data-aggregation on the Freebase graph.
The collection of music artists I'm using for the stacks example is gained using this simple acre-script:
http://acre.freebase.com/#!path=//collections.ma.user.dev/artists
-> results in http://collections.freebaseapps.com/artists
2. Visualization
--------------------------------------------------------------------------------
Now that you have a ready-to-be-visualized collection you can start implementing
a visualization, or use that aggregated data to power an existing vis.
The Unveil.js visualization should operate directly on the Collection passed to
the constructor. If I 've got it right you shouldn't need additional
data-structures for holding domain data (except for your visualization's state, of course) .
For querying within a Collection (which happens in memory) you can just traverse
the graph. Since every item / property / value has a unique key you can efficiently
access items in O(1).
Here's some more documentation regarding Collections I haven't migrated to the unveil doc page:
http://github.com/michael/unveil/tree/master/src/collection
There's also a Criterion API for querying data within a collection.
http://github.com/michael/unveil/blob/master/test/collection/testsuit...
And there's the concept of collection Transformers. Transformers turn collections into modified collections.
http://github.com/michael/unveil/tree/master/src/collection/transformers
DataGraph API
================================================================================
You'd want to use the DataGraph API when it comes to visualizing linked data.
The DataGraph format takes the idea of the Semantic Web, tries to reduce the
complexity and applies the concepts if RDF to a local visualization scenario.
Collection API
================================================================================
Collections are the main building block of the toolkit. A *Collection* is a simple
data abstraction format where a data-set under investigation conforms to a
collection of data items that describes all facets of the underlying data in a
simple and universal way. You can think of a *Collection* as a table of data,
except it provides precise information about the data contained (meta-data).
*Collections* are represented as a JSON string, which serves as an exchange format.
Since JSON is heavily used in web-services, its perfectly suited for usage in a
cloud-like scenario. Your collections can be constructed on the fly using live
data from web services that either provides data directly in the Collection format
or through a translator service that serves as an adapter for an existing service.
After passing the raw format to the *Collection* constructor, they are
internally represented as a network of nodes (a graph so to say), that allows
efficient operations on the *Collection* by traversing the graph instead of
iterating over all items, values etc. Also operations like filtering, grouping
etc. are already supported.
Construction
--------------------------------------------------------------------------------
$ var countries = new Collection({
$ "properties": "properties": {
$ "name": {
$ "name": "Country Name",
$ "type": "string",
$ "unique": true
$ },
$ "official_language": {
$ "name": "Official language",
$ "type": "string",
$ "unique": true
$ },
$ "form_of_government": {
$ "name": "Form of governmennt",
$ "type": "string",
$ "unique": false
$ },
$ "currency_used": {
$ "name": "Currency used",
$ "type": "string",
$ "unique": true
$ },
$ "population": {
$ "name": "Population",
$ "type": "number",
$ "unique": true
$ },
$ "gdp_nominal": {
$ "name": "GDP nominal",
$ "type": "number",
$ "unique": true
$ },
$ "area": {
$ "name": "Area",
$ "type": "number",
$ "unique": true
$ },
$ "date_founded": {
$ "name": "Date founded",
$ "type": "date",
$ "unqiue": true
$ }
$ },
$ "items": {
$ "arg": {
$ "name": "Argentina",
$ "official_language": "Spanish Language",
$ "form_of_government": [
$ "Federal republic",
$ "Presidential system"
$ ],
$ "currency_used": "Argentinian Peso",
$ "population": 39745613,
$ "gdp_nominal": 338700000000.0,
$ "area": 2780403.0,
$ "date_founded": "1816-07-09"
$ },
$ ...
$ },
$ });
The *Collection* constructor takes a collection represented as a JavaScript object,
which conforms to a parsed *JSON Collection String*. Once created you can query
the information contained.
The API features a simple object model for working with such in-memory
collections. The *Collection* object gives you access to the properties and
items contained.
Please make yourself familiar with the *Node API*, which is the data
structure used for modeling the internal structure of a collection, which is a
graph. Be aware that *Collection*, *Property*, *Item* and *Value* objects inherit
from *Node*, so the full *Node API* is available on such objects.
Properties
--------------------------------------------------------------------------------
Meta-data (data about data) is represented as a set of properties that belongs
to a collection. A *Property* (cmp. a column in a table) holds a key, a name
(cmp. a header of a column) and a type (telling whether the data is numeric or
textual, etc.).
**Access the Collection's properties:**
$ var properties = countries.all('properties'); // => SortedHash
**You can also access them directly:**
$ var population = countries.get('properties', 'population');
**And you can use property inspection:**
$ population.type; // => 'string'
$ population.name; // => 'Population'
$ population.unique; // => true
Items
--------------------------------------------------------------------------------
An item of the collection conforms to a row in a data table, except one ‘cell’
can have arbitrary many values (non-unique attributes).
**List all items:**
$ var items = countries.all('items'); // => SortedHash containing Item objects
**Or access them directly:**
$ var argentina = countries.get('items', 'arg'); -> Item#arg
**Inspect item values:**
$ argentina.value('name'); // => 'Argentina'
$ argentina.value('currency_used'); // => 'Argentinian Peso'
**Non-unique properties have more that one value:**
$ argentina.values('form_of_government');
$ // => [String#Federal_Republic, String#Presidential_system]
**With *SortedHash#each* you can easily iterate over values:**
$ argentina.values('form_of_government').each(function(index, gf) {
$ gf; // => e.g. 'Presidential System'
$ });
Values
--------------------------------------------------------------------------------
You can not only view values on a raw level but also as Nodes, which provide
useful meta-information about connections etc.
**List all items:**
$ var items = countries.all('items'); // => SortedHash containing Item objects
**Inspect the value 'Federal republic':**
$ federal_republic = argentina.all('form_of_government').first();
$ // => Node#Federal_Republic
**Which other countries also have this government form?**
$ federal_republic.all('items'); // => [Node#austria, Node#usa]
Set operations
--------------------------------------------------------------------------------
Since a *SortedHash* conforms to a set in mathematical respect, some interesting
operations can be performed.
$ var english = countries.all('items').select(function(key, i) {
$ return i.value('official_language') === 'English';
$ });
$
$ var french = countries.all('items').select(function(key, i) {
$ return i.value('official_language') === 'French';
$ });
$
$ // english and french speaking countries
$ var english_and_french = english.intersect(french); // => [Node#canada]
$
$ // english or french speaking countries
$ var english_or_french = english.union(french);
$ // => [Node#uk, Node#france, Node#Switzerland, ...]
Transformers [$TRANSFORMERS]
--------------------------------------------------------------------------------
Transformers are used to do operations on the desired *Collection*. A commonly
used one is the group transformation.
The following code does a grouping by the *official_language* property and sums
up all numeric properties (like population, area). What you get is a modified
collection that shows aggregated values for all occurring languages.
$ var languages = countries.transform('group', {
$ property: 'official_language',
$ aggregator: 'SUM'
$ });
**The resulting collection looks like this:**
$ {
$ "properties": "properties": {
$ "official_language": {
$ "name": "Official language",
$ "type": "string",
$ "unique": true
$ },
$ "population": {
$ "name": "Population",
$ "type": "number",
$ "unique": true
$ },
$ "gdp_nominal": {
$ "name": "GDP nominal",
$ "type": "number",
$ "unique": true
$ },
$ "area": {
$ "name": "Area",
$ "type": "number",
$ "unique": true
$ }
$ },
$ "items": {
$ "English": {
$ "population": 397445613,
$ "gdp_nominal": 4341700000000.0,
$ "area": 2780403.0,
$ },
$ "German": {
$ "population": 91560000,
$ "gdp_nominal": 4341700000000.0,
$ "area": 2780403.0,
$ },
$ ...
$ }
$ };
Transformers are non-destructive. The original *Collection* is not modified unless
you re-assign the result.
Implement your own Transformer
--------------------------------------------------------------------------------
All you have to do is to assign a new *Property* on the pv.Collection.transformers
object, which holds a transformer function. This function takes an input
collection and a params hash.
$ pv.Collection.transformers.group = function(c, params) {
$ // hardcore grouping action that yields a modified output collection
$ return outputColletion;
$ };
Have a look at the implementation of the "Group Transformer"[http://github.com/michael/unveil/blob/master/src/collection/transformers/group.js], to see how it's done.
**Transformer specification:**
You need to define a specification for your *Transformer*, which gives it a
human readable name and describes the parameters your transformation takes.
$ pv.Collection.transformers.group.label = "Group By";
$ pv.Collection.transformers.group.params = {
$ properties: {
$ name: "Property",
$ type: "property_list"
$ },
$ aggregator: {
$ name: "Aggregator Function",
$ type: "aggregator"
$ }
$ }
Available Collections
--------------------------------------------------------------------------------
Some sample collections are available through "Collectionize"[http://github.com/michael/collectionize], a dedicated
aggregator service, that translates interesting web services to the *Collection* format.
**Currently available:**
* "Countries fetched from Freebase.com"[http://collections.quasipartikel.at/countries]
* "Last.fm Playlists"[http://collections.quasipartikel.at/playlists]
Visualization API [$VIS]
================================================================================
The *Visualization API* provides a simple abstraction layer for visualizations to ease
the process of creating re-usable data-driven visualizations.
The appearance of a visualization is determined by the underlying data rather than by
user defined plotting options. Visualizations directly access data trough a well defined
interface, the *Collection API*, so there's no longer a gap between domain data and
data used by the visualization engine.
Such visualization can be re-used in terms of putting arbitrary data in.
This works as long as the data is a valid *Collection* and satisfies the
visualization specification (some visualizations exclusively use numbers as their
input, others use dates (e.g. Timeline plots), and so on...).
Usage
--------------------------------------------------------------------------------
$ // load some data (represented as a Collection)
$ c = new uv.Collection(countries);
$
$ // construct a visualization based on that data
$ vis = new uv.Linechart(c, {
$ measures: ['population'],
$ params: {scale: 'linear'}
$ });
$ vis.render();
Creating visualizations
--------------------------------------------------------------------------------
In order to create your own visualizations you need to setup a new class that
inherits from *uv.Visualization*.
$ var MyChart = uv.Visualization.extend({
$ constructor: function(collection, options) {
$ uv.Visualization.call(this, collection, options);
$ },
$ render: function() {
$ // hardcore rendering action
$ }
$ });
All you have to do is to implement *render()*. It's totally up to you whether you
want to use the included Scene API or any other visualization library (I can recommend "Protovis"[http://protovis.org], "Processing.js"[http://processingjs.org] and "Scene.js"[http://scenejs.org]) or
work with the native API's (Canvas, SVG, WebGL).
Visualization Specification
................................................................................
There are various types of visualizations. Some exclusively use numbers as their
input, some use dates (e.g. Timeline plots) others visualize relationships between
data items (e.g. which countries share the same currency). There are further
visualizations that use various combinations of measure types.
In order to verify that the current selection of measures can be displayed by the
chosen visualization you have to define a specification like this:
$ // Displays 1..n number properties
$ uv.Barchart.spec = {
$ measures: [
$ {
$ types: ['number'],
$ unique: true,
$ cardinality: 1
$ },
$ {
$ types: ['number'],
$ unique: true,
$ cardinality: "*"
$ }
$ ]
$ };
**Have a look at the implementations of *Scatterplot* and *Linechart* for reference:**
* "Scatterplot"[http://github.com/michael/unveil/tree/master/src/visualization/visualizations/scatterplot.js]
* "Linechart"[http://github.com/michael/unveil/tree/master/src/visualization/visualizations/linechart.js]
Scene API [$SCENE]
================================================================================
Inspired by various great visualization libraries (Protovis, Processing.js), I
created my own rather low level graphical library that is basically an
implementation of a Scenegraph on top of the *HTML5 Canvas API*.
It's more a framework that helps you managing complexity rather than a full-featured
graphical visualization library.
**I focussed on two core principles:**
* Object oriented
* Declarative
Object oriented in terms of thinking in graphical objects and modularizing
code, declarative in terms of using, configuring and combining existing *Actors*
(graphical objects) and attach them to the Scenegraph.
**Creating a scene is easy:**
$ var scene = new uv.Scene({
$ fillStyle: '#ccc'
$ });
Actors
--------------------------------------------------------------------------------
Once you have constructed your *Scene* object, you can start adding actors.
*Actors* can be primitive graphical objects (like a Bar, a Line, or a Dot) or higher
level objects that combine lower level ones (e.g. a Hyperbolic Tree). Actors
typically take properties in their constructor. However for higher level objects
you probably want them to be constructed with real domain data instead of simple
graphical oriented properties (width, height etc.). You can decide on your own
how you want to shape the interface.
**Add an Actor (Bar) to the scene:**
$ var bar = new uv.Bar({
$ x: 30,
$ y: 50,
$ width: 30,
$ height: 80,
$ fillStyle: 'darkblue'
$ });
**Add an additional bar as a child of the bar just created:**
$ bar.add(new uv.Bar({
$ x: 50,
$ y: 20,
$ width: 20,
$ height: 80,
$ fillStyle: 'lightblue'
$ }));
The x and y coordinates are relative to the parent object. So an object does not
know where it is located in the coordinate-space. It just renders itself at
position 0,0. The positioning is done through matrix transformations, where for
each object the current context (transformation matrix) is being calculated on
every frame. That's how a SceneGraph works.
**Specify an output display:**
$ scene.display({
$ container: $('#plotarea'),
$ width: 800,
$ height: 300,
$ zooming: true,
$ paning: true
$ });
The scene (world-coordinates) can be projected to one or many displays (canvas elements), that
have a local coordinate system. Each display can be modified (zoomed, paned, etc.) independently.
This conforms to a view transformation in computer-game-engine-like API's (camera analogy).
You can see multiple displays in action "here"[http://quasipartikel.at/unveil/examples/multiple_displays.html].
**Start the scene:**
$ // defaults to 10 frames per second
$ scene.start();
The scene automatically refreshes each attached display appropriately (on every frame).
**Create your own actors:**
Creating visualizations using the *Scene API* most often means implementing your own *Actors*.
I'd see the creation of custom Actors as a fundamental part of the visualization
creation process. So instead of combining only existing pre-implemented objects, you're
encouraged to create your own ones, suitable for your needs.
**Let's re-create the Bar Actor from scratch, and add some interaction and animation later:**
$ uv.Bar = function(properties) {
$ // super call
$ uv.Actor.call(this, uv.extend({
$ width: 30,
$ height: 50,
$ strokeWeight: 2,
$ strokeStyle: '#000',
$ fillStyle: '#ccc'
$ }, properties));
$ };
**Every Actor inherits from uv.Actor:**
$ uv.Bar.prototype = uv.extend(uv.Actor);
**Implement a draw method, which takes a Canvas 2D context:**
$ uv.Bar.prototype.draw = function(ctx) {
$ ctx.fillRect(0, 0, this.properties.width, this.properties.height);
$ };
Interaction
--------------------------------------------------------------------------------
Interaction is key in visualizations. Therefore Unveil.js aims to provide an
abstraction for implementing interaction on your *Actors*. Unlike in SVG, with
the Canvas API you can't attach event handlers to shapes directly. Instead
you need to detect on your own, which objects are currently under the cursor.
Usually you'd do this with some math, but there's a simpler approach that
utilizes *isPointInPath()*.
With *isPointInPath()* you can check if the current mouse-position is inside
the current working path.
To make use of this you need to equip your Actors with an additional
*drawMask()* method.
**Let's add some interaction to our Bar:**
$ uv.Bar.prototype.drawMask = function(ctx) {
$ ctx.beginPath();
$
$ ctx.moveTo(0, 0);
$ ctx.lineTo(this.properties.width, 0);
$ ctx.lineTo(this.properties.width, this.properties.height);
$ ctx.lineTo(0, this.properties.height);
$ ctx.lineTo(0, 0);
$ };
This simply draws an invisible rectangle. If you have a more complex object like
a star-shape you can use a rectangle (also known as a bounding-box) as well, to
mask your object for interaction. However, that's for the lazy folks. ;-)
Actors that have a *drawMask()* implementation can then be easily checked
against the current cursor position.
**That's what is going on behind the curtain:**
$ uv.Actor.prototype.checkActive = function(ctx, mouseX, mouseY) {
$ if (this.drawMask && ctx.isPointInPath) {
$ this.drawMask(ctx);
$ if (ctx.isPointInPath(mouseX, mouseY))
$ this.active = true;
$ else
$ this.active = false;
$ }
$ };
Animation
--------------------------------------------------------------------------------
It's easy to add animation to your objects too. I've added a "Tween class"[http://quasipartikel.at/tween/]
I created some time ago to animate properties over time.
**To animate the height property of a Bar you simply use a Tween for that:**
$ uv.Bar = function(properties) {
$ ...
$ this.t = new uv.Tween({
$ object: this.properties,
$ property: 'height'
$ });
$ };
**The *updateHeight()* method is used to trigger the Tween:**
$ uv.Bar.prototype.updateHeight = function(newHeight) {
$ this.t.continueTo(newHeight, 1.5);
$ };
**For now you need to manually trigger a Tween tick using the *Actor#update()* method:**
$ uv.Bar.prototype.update = function() {
$ this.t.tick();
$ };
**In your sketch you can use *setTimeout()* or *setInterval()* to trigger the *updateHeight()* method:**
$ setInterval(function() {
$ bar.updateHeight(70);
$ }, 1000);
Here's an example of "Moving Random Bars"[http://quasipartikel.at/unveil/examples/random_bars.html],
that feature interaction and animation.
Commands
--------------------------------------------------------------------------------
*Commands* are used to modify properties on the scene. They can be executed
one or many times, and they can be unexecuted to recover the original state.
Such commands are a powerful abstraction for modifying state. Implement your own
commands whenever it makes sense.
What always annoyed me is the problem of high CPU-consumption that canvas-based visualizations
typically have. The reason for that is, that if your scene runs on 60 fps, then even when there's
no animation or interaction taking place, the *render()* method is called 60 times a second.
**I could solve this by implementing a *RequestFramerate* command:**
$ uv.cmds.RequestFramerate = function(scene, opts) {
$ this.scene = scene;
$ this.requests = 0;
$ this.framerate = opts.framerate;
$ this.originalFramerate = this.scene.framerate;
$ };
$
$ uv.cmds.RequestFramerate.className = 'RequestFramerate';
$
$ uv.cmds.RequestFramerate.prototype.execute = function() {
$ this.requests += 1;
$ this.scene.framerate = this.framerate;
$ };
$
$ uv.cmds.RequestFramerate.prototype.unexecute = function() {
$ this.requests -= 1;
$ if (this.requests <= 0) {
$ this.scene.framerate = this.originalFramerate;
$ }
$ };
**Having that command in place, we need to register it on the scene: **
$ scene.register(uv.cmds.RequestFramrate, { framerate: 60 });
**Then this command can be excuted and unexecued on demand.:**
$ t = new uv.Tween({...});
$ t.on('start', function() { that.scene.execute(uv.cmds.RequestFramerate); });
$ t.on('finish', function() { that.scene.unexecute(uv.cmds.RequestFramerate); });
**It works like this:**
The scene by default runs in idle mode (say 10fps),
which is enough to deal with mouse interaction. If an operation (in this case
a Motion Tween) needs high speed (60fps) it requests it, like if it would
request a resource.
The *Tween* class (like any other operation that needs full power) needs callbacks
for start and finish events, that can be used to request high speed (on start) and
release this demand when 'finish' is fired.
It basically works like a semaphore, where each request increments a *requests*
counter, and each release decrements it. When all motion tweens have finished
*requests* is zero. The current framerate then depends on the value of
*requests* (0 = idle mode, > 0 = highspeed / full throttle mode).
I've updated the "stacks example"[http://quasipartikel.at/unveil/examples/stacks.html],
that now uses 60fps on demand (10fps per default). Thankfully lots of CPU cycles could
be saved. ;-)
Modification Matrix
--------------------------------------------------------------------------------
While most often specifying properties (x, y, scaleX, scaleY, rotation) on the
Actor suffices, there may be cases where you need more control. Therefore
Actors expose a so called *Modification Matrix*, which can be directly modified
by the user.
**To scale and rotate an object around a point, you can specify a series of matrix transforms:**
$ var b = new uv.Bar({...});
$ // move the coordinate system to the desired point
$ b.translate(40,40);
$ // scale around this point (= new origin)
$ b.scale(1.5, 1.5);
$ // rotate 45°
$ b.rotate(Math.PI/4);
$ // move the coordinate system back
$ b.translate(-40, -40);
To calculate the resulting transformation matrix for drawing, it is
initialized with the values of the specified properties and then multiplied with
the modification matrix.
Examples
--------------------------------------------------------------------------------
* "Stacks"[http://quasipartikel.at/unveil/examples/stacks.html]
* "Random Bars"[http://quasipartikel.at/unveil/examples/random_bars.html]
* "Multiple displays"[http://quasipartikel.at/unveil/examples/multiple_displays.html]
Hints
--------------------------------------------------------------------------------
The Scene API related code is pretty small (~ 400 LOC). I don't plan to provide
a full-featured graphic library with helper functions, since there are
existing libraries, that do a perfect job. I recommend using Protovis along with
the Scene API. Actually, this library was created because Protovis does not
support the canvas element. I also wanted an easier way to deal with interaction.
To prevent from verbose and messy code, I do not provide any backward
compatibility for older browsers. I'm trying to stay on the edge of technology.
Therefore I focus on supporting the most recent versions of Google Chrome,
Firefox, Safari. I'll probably support Internet Explorer 9 as well, since their
Canvas implementation looks promising. Currently mouse interaction is not working
in Firefox. Please use a webkit-based browser for the moment.
Node API [$NODE]
================================================================================
Node (not to be confused with Node.js) is a JavaScript Graph implementation that
hides graph complexity from the interface. It introduces properties, which group
types of edges together. Therefore multi-partit graphs are possible without any
hassle. Every Node simply contains properties which conform to outgoing edges.
It makes heavy use of hashing through JavaScript object properties to allow
random access whenever possible.
The Node API heavily relies on *SortedHash*, please have a look at
the documentation before you start.
Construction
--------------------------------------------------------------------------------
$ // Initialize a plain Node
$ var austria = new Node(),
$ germany = new Node(),
$ uk = new Node();
$
$ // initialize with raw Value (raw values are typically stored in leave nodes)
$ var eu = new Node({value: 'European Union'}),
$ austrian = new Node({value: 'Austrian'}),
$ english = new Node({value: 'English'}),
$ german = new Node({value: 'German'}),
$ barroso = new Node({value: 'Barroso'});
Connect nodes through properties
--------------------------------------------------------------------------------
$ austria.set('languages', 'at', austrian);
$ austria.set('languages', 'ger', german);
$
$ eu.set('president', 'barroso', barroso);
$
$ // Backlinks
$ german.set('spoken_in', {
$ 'at': austria,
$ 'de': germany
$ });
Get connected nodes
--------------------------------------------------------------------------------
$ austria.all('languages') // => [Node#austrian, Node#german]
$ eu.first('president') // => [Node#barroso]
$ german.all('spoken_in') // => [Node#austria, Node#germany]
Iteration
--------------------------------------------------------------------------------
each:
$ austria.all('languages').each(function(index, node) {
$ node; // => Node#at | Node#ger
$ index; // => 0 | 1
$ });
eachKey:
$ austria.all('languages').eachKey(function(key, node) {
$ node; // => Node#at | Node#ger
$ key; // => 'at' | 'ger'
$ });
Sorted Hash API [$SORTEDHASH]
================================================================================
Unveil.js features a *SortedHash* data structure that provides a simple layer of
abstraction for managing Sorted Hashes in JavaScript. It's heavily used
throughout the framework.
Insertion
--------------------------------------------------------------------------------
$ var items = new SortedHash();
$ items.set('at', 'Austria');
$ items.set('de', 'Germany');
Access
--------------------------------------------------------------------------------
**Hash Semantics:**
$ items.get('at') // => 'Austria';
$ items.get('de') // => 'Germany';
**Array Semantics:**
$ items.at(0); // => 'Austria'
$ items.at(1); // => 'Germany'
$ items.length; // => 2
Iteration
--------------------------------------------------------------------------------
**each:**
$ items.each(function(index, value) {
$ value; // => 'Austria', 'Germany'
$ index; // => 0, 1
$ });
**eachKey:**
$ items.eachKey(function(key, value) {
$ value; // => 'Austria', 'Germany'
$ key; // => 'at', 'de'
$ })
Operations
--------------------------------------------------------------------------------
**sort:**
$ var desc = function(item1, item2) {
$ return item1.value === item2.value
$ ? 0 : (item1.value > item2.value ? -1 : 1);
$ },
$ sortedItems;
$
$ sortedItems = items.sort(descendingOrder);
**map:**
$ var mappedItems = items.map(function (item) {
$ return item.slice(0, 3);
$ });
$
$ // leave original SortedHash untouched
$ mappedItems.at(0) // => 'Aus';
$ mappedItems.at(1) // => 'Ger';
This returns a SortedHash in descending order, while the original remains
untouched.
**select:**
$ var selectedItems = items.select(function (key, item) {
$ return item === 'Austria';
$ });
$
$ selectedItems.at(0) // => 'Austria';
$ selectedItems.length; // => 1;
**intersect:**
$ var items2 = new SortedHash(),
$ intersectedItems;
$
$ items2.set('fr', 'France');
$ items2.set('at', 'Austria');
$
$ intersectedItems = items.intersect(items2);
$
$ intersectedItems.length; // => 1
$ intersectedItems.get('at'); // => 'Austria'
**union:**
$ var items2 = new SortedHash(),
$ unitedItems;
$
$ items2.set('fr', 'France');
$ items2.set('at', 'Austria');
$
$ intersectedItems = items.intersect(items2);
$
$ unitedItems.length; // => 3
$ unitedItems.get('at'); // => 'Austria'
$ unitedItems.get('de'); // => 'Germany'
$ unitedItems.get('fr'); // => 'France'
**Method chaining:**
$ var mappedAndSortedItems = items.map(function (item) {
$ return item.slice(0, 3);
$ })
$ .sort(descendingOrder);
$
$ selectedItems.at(0) // => 'Ger';
$ selectedItems.at(2) // => 'Aus';