This repository was archived by the owner on Jun 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy path2011-12-01-PomaxGuide.html
1486 lines (1232 loc) · 51.9 KB
/
2011-12-01-PomaxGuide.html
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
---
layout: default
desc: Pomax's guide to Processing.js
title: Pomax Guide
permalink: /articles/PomaxGuide.html
---
<script type="text/javascript">
function toggleContent(id) {
var e = document.getElementById(id);
if (e.style.display!="block") {
e.style.display = "block";
} else {
e.style.display = "none";
}
}
// sketch 1
function stop(id) {
var pjs = Processing.getInstanceById(id);
pjs.stop();
}
function play(id) {
var pjs = Processing.getInstanceById(id);
pjs.playSketch();
}
// sketch 2
function drawText(id) {
var pjs = Processing.getInstanceById(id);
var text = document.getElementById('ms2text').value;
pjs.drawText(text);
}
// sketch 3
function showXYCoordinates(x, y) {
document.getElementById('xcoord').value = x;
document.getElementById('ycoord').value = y;
}
// sketch 4
var bound = false;
function bindJavascript() {
var pjs = Processing.getInstanceById('mysketch3');
if(pjs != null) {
pjs.bindJavascript(this);
bound = true;
}
if (!bound) {
setTimeout(bindJavascript, 250);
}
}
bindJavascript();
// sketch 5
function loadPointsJS(id, button) {
button.disabled = "disabled";
var pjs = Processing.getInstanceById(id);
var points = pjs.getPoints();
points.add(new pjs.Point(10,10));
points.add(new pjs.Point(10,190));
points.add(new pjs.Point(190,190));
points.add(new pjs.Point(190,10));
pjs.draw();
}
// sketch 6
function loadPointsJSON(id, button) {
button.disabled = "disabled";
var pjs = Processing.getInstanceById(id);
var json = "{'points' : [{'x': 10, 'y': 10}, {'x': 190, 'y': 10}, {'x': 190, 'y': 190}, {'x': 10, 'y': 190}]}";
var data = eval("("+json+")");
if (data) {
for (p=0, end=data.points.length; p<end; p++) {
var point = data.points[p];
pjs.addPoint(point.x, point.y);
}
}
}
// sketch 7
function loadPointsXML(id, button) {
button.disabled = "disabled";
var pjs = Processing.getInstanceById(id);
var xml = "<xml><point x='10' y='10'/><point x='190' y='50'/><point x='10' y='90'/><point x='190' y='140'/><point x='10' y='190'/></xml>";
pjs.buildFromXML(xml);
}
</script>
<div>
<h2>Pomax's guide to Processing.js</h2>
<ul id="idx">
<li><a href="#faq">what is Processing</a></li>
<li><a href="#onpage">putting a sketch on the page</a></li>
<li><a href="#inpage">putting a sketch inline on the page</a></li>
<li><a href="#interface">making your sketch and your page see each other</a>
<ul>
<li><a href="#jstosketch">making javascript see your sketch</a></li>
<li><a href="#sketchtojs">making your sketch "see" javascript</a></li>
</ul>
</li>
<li><a href="#jsobj">passing complex objects from javascript to your sketch</a>
<ul>
<li><a href="#pobj">passing data using Processing itself</a></li>
<li><a href="#json">passing data using JSON</a></li>
<li><a href="#xml">passing data using XML</a></li>
<li><a href="#svg">passing SVG data</a></li>
<li><a href="#jobjs">passing genuine javascript objects</a></li>
</ul>
</li>
<li><a href="#graphic">Processing.js as javascript graphics library</a></li>
<li><a href="#more">more information</a></li>
</ul>
<p>This page tries to explain how to quickly and (as) correctly (as possible) use
Processing sketches on webpages. The information is based on the work done by
the <a href="/">processing.js</a> group.</p>
<p>This information on this page reflects the best of my knowledge anno November
2010, and processing.js becomes more and more complete, so it is possible that the
information on this page changes over time. Should you spot any incompletenesses
or blatant mistakes, please contact me at
<!-- ah, the wonder of making a scrape-proof email address -->
<a href="http://www.nihongoresources.com/general/contact.html">pomax<i> at
</i>nihongoresources.<i>com,</i></a>
with the obvious substitutions in place to make it a legal email address.</p>
<h3 id="faq" onclick="toggleContent('faq')">What is Processing?</h3>
<p>The "Processing" language (also referred to as "P5") is a programming language
with a focus on data visualisation. Of course, "data" is a loose concept, and
Processing can be used for anything from drawing a few lines and circles on a
screen, to full blown interactive animations. In fact, a basic Processing program
is two lines of code, and will already play an animation:</p>
{% highlight java linenos %}
void setup() { size(..., ...); }
void draw() {}{% endhighlight %}
<p>Of course this program doesn't show you anything, because all it does is set up
the visual context to have a certain width and height (indicated in the setup
method as the size(...,...) instruction) and then calls draw() every few milliseconds.
Of course, draw() is empty, so it won't actually show you anything. A more useful
minimal program would be a "hello world" program, but I hate those because they only
show a programming language can write text, and that's pretty much the least interesting
feature of any programming language. Instead let's look at a minimal program that makes
sense for a data visualisation language:</p>
{% highlight java linenos %}
float framerate = 24; // our "sketch" will have a framerate of 24 frames per second.
int ball_x; // ball administration: x coordinate
int ball_y; // ball administration: y coordinate
int ball_radius = 20; // ball administration: ball radius
void setup() {
size(200,200); // set draw area size
frameRate(framerate); // set animation framerate
ball_x = width/2; // set the initial ball coordinates
ball_y = ball_radius; // set the initial ball coordinates
stroke(#003300); // set the default shape outline colour
fill(#0000FF); // set the default shape fill colour
}
void draw() {
// compute the ball height for this frame
float bounce_height = height/2 * abs(sin(PI*frameCount/framerate));
// because the top of the screen is 0, and the bottom is "height",
float ball_height = height - (bounce_height+ball_radius);
// clear the drawing area
background(#FFFFEE);
// set the new ball y position
ball_y = (int) (ball_height);
// draw the ball
ellipse(ball_x,ball_y,ball_radius,ball_radius);
}{% endhighlight %}
<canvas id="sketch1" data-processing-sources="/sketches/sketch1.pde" style="border: 1px solid blue;"></canvas>
<div>
<span style="font-size:80%">play controls:</span>
<button type="button" onclick="stop('sketch1')" class="Pomax">■</button>
<button type="button" onclick="play('sketch1')" class="Pomax">▶</button>
</div>
<p>This looks a bit long for a minimal program, but then again, this actually <em>does</em>
something: it shows us a ball that bounces up and down, taking one second for each
bounce. It shows a few aspects of Processing too: every variable is strongly typed.
So you have to indicate what you'll be using a variable for, and you can choose from:</p>
<ul>
<li>boolean, a binary value that can be either true or false</li>
<li>byte, an 8-bit value</li>
<li>char, a byte representing an ascii character</li>
<li>color, a type specific to Processing, representing an on-screen color</li>
<li>int, a 32 bit signed integer number</li>
<li>long, a 64 bit signed integer number</li>
<li>float, a 32 bit signed decimal number</li>
<li>double, a 64 bit signed decimal number</li>
</ul>
<p>And of course there are also the typical complex data types:</p>
<ul>
<li>Object, a catch-all data type for things that are complex data types.</li>
<li>String, a text string (stored as UTF-16).</li>
<li>ArrayList, a list structure for arbitrary values with add/remove functionality.</li>
<li>HashMap, a structure that can store {<unique key>, <arbitrary value>} pairs.</li>
<li>XMLElement, a convenient XML-mirroring object.</li>
</ul>
<p>You'll see why this last one turns out to be really useful later on.</p>
<p>Coming back to the minimally functional example of a Processing program, or "sketch",
there are also some examples of Processing' own API at work. The following methods are
native Processing calls:</p>
<ul>
<li>size(int, int), sets the drawing area dimensions, and the global "width" and "height" values.</li>
<li>frameRate(int), sets the refresh rate for the drawing area, and the frameRate value.</li>
<li>stroke(color), sets the shape outline color.</li>
<li>fill(color), sets the shape fill color.</li>
<li>abs(number), computes the absolute value of any number.</li>
<li>sin(number), computes the sinoid value based on any number (treated as radians).</li>
<li>background(color), sets every pixel of the drawing area to the specified color.</li>
<li>ellipse(int, int, int, int), draws an ellipse on the drawing area.</li>
</ul>
<p>The Processing API is in fact quite expansive (See
<a href="http://processing.org/reference">http://processing.org/reference</a> for the full
list), but it can't cover everything. Luckily it supports object oriented programming, so
that our previous example can also be written as an object oriented sketch:</p>
{% highlight java linenos %}
Bouncer bouncer;
void setup() {
size(200,200);
frameRate(24);
stroke(#003300);
fill(#0000FF);
bouncer = new Ball(width/2,20,20);
}
void draw() {
bouncer.computeNextStep(width, height, frameRate);
background(#FFFFEE);
bouncer.draw();
}
interface Bouncer {
void computeNextStep(int width, int height, float framerate);
void draw();
}
class Ball implements Bouncer
{
int x,y,radius;
int step = 0;
Ball(int x, int y, int r) {
this.x = x;
this.y = y;
this.radius = r;
}
void computeNextStep(int sketch_width, int sketch_height, float frame_rate) {
step++;
float sin_value = abs(sin(PI*step/(float)frame_rate));
float bounce_height = sketch_height/2 * sin_value;
float ball_height = sketch_height - (bounce_height + radius);
y = (int) (ball_height);
}
void draw() {
ellipse(x,y,radius,radius);
}
}{% endhighlight %}
<canvas id="sketch2" data-processing-sources="/sketches/sketch2.pde" style="border: 1px solid blue;"></canvas>
<div>
<span style="font-size:80%">play controls:</span>
<button type="button" onclick="stop('sketch2')" class="Pomax">■</button>
<button type="button" onclick="play('sketch2')" class="Pomax">▶</button>
</div>
<p>Instead of doing everything in the draw() function, the object oriented approach
tucks all the code that relates to computing the ball's position in the definition
for what we consider a "Ball". To be good object oriented programmers, we've also said
that things that are a Ball are also a Bouncer, and this lets us extend our sketch very
easily to instead of a bouncing ball, have a bouncing box by keeping almost everything
the same, and adding a new class Box that's a Bouncer:</p>
{% highlight java linenos %}
void setup() {
...
bouncer = new Box(width/2,20,20,20);
}
class Box implements Bouncer
{
int x,y,w,h;
int step=0;
Box(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
void computeNextStep(int sketch_width, int sketch_height, float frame_rate) {
step++;
float sin_value = abs(sin(PI/2.0 + (PI*step/(float)frame_rate)));
float bounce_height = sketch_height/2 * sin_value;
float ball_height = sketch_height - (bounce_height + h);
y = (int) (ball_height);
}
void draw() {
rect(x,y,w,h);
}{% endhighlight %}
<canvas id="sketch3" data-processing-sources="/sketches/sketch3.pde" style="border: 1px solid blue;"></canvas>
<div>
<span style="font-size:80%">play controls:</span>
<button type="button" onclick="stop('sketch3')" class="Pomax">■</button>
<button type="button" onclick="play('sketch3')" class="Pomax">▶</button>
</div>
<p>All of a sudden we have a bouncing box, that starts from a falling position instead
of from the ground, and we didn't have to modify the master draw() function for it!
In fact, let's just use a group of bouncing things:</p>
{% highlight java linenos %}
Bouncer[] bouncer = new Bouncer[3];
void setup() {
...
bouncer[0] = new Ball(width/3-20,20,20);
bouncer[1] = new Box(width/2-10,20,20,20);
bouncer[2] = new Ball((2*width/3)+20,20,20);
}
void draw() {
for(int b=0, end=bouncer.length; b<end;b++) {
bouncer[b].computeNextStep(width, height, frameRate);
}
background(#FFFFEE);
for(int b=0, end=bouncer.length; b<end;b++) {
bouncer[b].draw();
}
}
...{% endhighlight %}
<canvas id="sketch4" data-processing-sources="/sketches/sketch4.pde" style="border: 1px solid blue;"></canvas>
<div>
<span style="font-size:80%">play controls:</span>
<button type="button" onclick="stop('sketch4')" class="Pomax">■</button>
<button type="button" onclick="play('sketch4')" class="Pomax">▶</button>
</div>
<p>Fantastic, two bouncing balls and a bouncing box, bouncing counter-point to each
other. But it's not very interactive yet. Let's change it so that we can "hang on"
to bouncing things until we let go of them again. Processing allows interaction with
the keyboard and mouse, using what are known as "event handlers", methods that Processing
automatically calls for you when you use the keyboard or mouse. In this case we care
about mouse interaction, so we'll look at mousePressed and mouseReleased events:</p>
{% highlight java linenos %}
void mousePressed() {
for(int b=0, end=bouncer.length; b<end;b++) {
if(bouncer[b].mouseOver(mouseX, mouseY)) {
bouncer[b].mousePressed();
}
}
}
void mouseReleased() {
for(int b=0, end=bouncer.length; b<end;b++) {
bouncer[b].mouseReleased();
}
}
abstract class Bouncer
{
int x, y;
boolean canmove = true;
int step = 0;
abstract void computeNextStep(int width, int height, float framerate);
abstract void draw();
abstract boolean mouseOver(int mx, int my);
void mousePressed() { canmove = false; }
void mouseReleased() { canmove = true; }
}
class Ball extends Bouncer
{
int radius;
Ball(int x, int y, int r) {
this.x = x;
this.y = y;
this.radius = r;
}
void computeNextStep(int sketch_width, int sketch_height, float frame_rate) {
if(canmove) {
step = (int)((step+1) % frame_rate);
float sin_value = abs(sin(PI*step/(float)frame_rate));
float bounce_height = sketch_height/2 * sin_value;
float ball_height = sketch_height - (bounce_height + radius);
y = (int) (ball_height);
}
}
void draw() { ellipse(x,y,radius,radius); }
boolean mouseOver(int mx, int my) {
return sqrt((x-mx)*(x-mx) + (y-my)*(y-my)) <= radius;
}
class Box extends Bouncer
{
int w,h;
int step=0;
Box(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
void computeNextStep(int sketch_width, int sketch_height, float frame_rate) {
if(canmove) {
step = (int)((step+1) % frame_rate);
float sin_value = abs(sin(PI/2.0 + (PI*step/(float)frame_rate)));
float bounce_height = sketch_height/2 * sin_value;
float ball_height = sketch_height - (bounce_height + h);
y = (int) (ball_height);
}
}
void draw() { rect(x,y-h/2,w,h); }
boolean mouseOver(int mx, int my) {
return x<=mx && mx<=x+w && (y-h/2)<=my && my<=(y+h/2);
}
}{% endhighlight %}
<canvas id="sketch5" data-processing-sources="/sketches/sketch5.pde" style="border: 1px solid blue;"></canvas>
<div>
<span style="font-size:80%">play controls:</span>
<button type="button" onclick="stop('sketch5')" class="Pomax">■</button>
<button type="button" onclick="play('sketch5')" class="Pomax">▶</button>
</div>
<p>Because the Ball and Box classes will do the same thing on mouse interaction,
the interface Bouncer has been changed to an actual class too, to take care of some of
the shared functionality. Now if you click on anything that's a Bouncer it'll stop
moving until you let it go. Let's go one step further an just allow us to move the
bouncing things around, too.</p>
{% highlight java linenos %}
Bouncer[] bouncer = new Bouncer[3];
void setup() {
size(200,200);
frameRate(24);
stroke(#003300);
fill(#0000FF);
bouncer[0] = new Ball(width/3-20,20,20);
bouncer[1] = new Box(width/2-10,20,20,20);
bouncer[2] = new Ball((2*width/3)+20,20,20);
}
void draw() {
for(int b=0, end=bouncer.length; b<end;b++) {
bouncer[b].computeNextStep(width, height, frameRate);
}
background(#FFFFEE);
for(int b=0, end=bouncer.length; b<end;b++) {
bouncer[b].draw();
}
}
void mousePressed() {
for(int b=0, end=bouncer.length; b<end;b++) {
if(bouncer[b].mouseOver(mouseX, mouseY)) {
bouncer[b].mousePressed();
}
}
}
void mouseReleased() {
for(int b=0, end=bouncer.length; b<end;b++) {
bouncer[b].mouseReleased();
}
}
void mouseDragged() {
for(int b=0, end=bouncer.length; b<end;b++) {
bouncer[b].mouseDragged(mouseX, mouseY);
}
}
abstract class Bouncer
{
int x, y;
boolean canmove = true;
int step = 0;
int xoffset = 0;
int yoffset = 0;
void computeNextStep(int width, int height, float framerate) {
if(canmove) {
reallyComputeNextStep(width, height, framerate);
}
}
abstract void reallyComputeNextStep(int width, int height, float framerate);
abstract void draw();
abstract boolean mouseOver(int mx, int my);
void mousePressed() {
canmove = false;
}
void mouseReleased() {
canmove = true;
x += xoffset;
y += yoffset;
xoffset = 0;
yoffset = 0;
}
void mouseDragged(int mx, int my) {
if(!canmove) {
xoffset = mx-x;
yoffset = my-y;
}
}
}
class Ball extends Bouncer
{
int radius;
Ball(int x, int y, int r) {
this.x = x;
this.y = y;
this.radius = r;
}
void reallyComputeNextStep(int sketch_width, int sketch_height, float frame_rate) {
step = (int)((step+1) % frame_rate);
float sin_value = abs(sin(PI*step/(float)frame_rate));
float bounce_height = sketch_height/2 * sin_value;
float ball_height = sketch_height - (bounce_height + radius);
y = (int) (ball_height);
}
void draw() { ellipse(x+xoffset,y+yoffset,radius,radius); }
boolean mouseOver(int mx, int my) {
return sqrt((x-mx)*(x-mx) + (y-my)*(y-my)) <= radius;
}
}
class Box extends Bouncer
{
int w,h;
int step=0;
Box(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
void reallyComputeNextStep(int sketch_width, int sketch_height, float frame_rate) {
step = (int)((step+1) % frame_rate);
float sin_value = abs(sin(PI/2.0 + (PI*step/(float)frame_rate)));
float bounce_height = sketch_height/2 * sin_value;
float ball_height = sketch_height - (bounce_height + h);
y = (int) (ball_height);
}
void draw() { rect(x+xoffset,(y-h/2)+yoffset,w,h); }
boolean mouseOver(int mx, int my) {
return x<=mx && mx<=x+w && (y-h/2)<=my && my<=(y+h/2);
}
}{% endhighlight %}
<canvas id="sketch6" data-processing-sources="/sketches/mysketch.pde" style="border: 1px solid blue;"></canvas>
<div>
<span style="font-size:80%">play controls:</span>
<button type="button" onclick="stop('sketch6')" class="Pomax">■</button>
<button type="button" onclick="play('sketch6')" class="Pomax">▶</button>
</div>
<p>And with that, on to the original topic of this article: using Processing on web pages</p>
<h3 id="onpage" onclick="toggleContent('onpage')">Putting a sketch on the page</h3>
<p>The great thing about Processing is that it can be used on webpages. Traditionally,
you would convert your sketch to a java applet, and embed that on a page, but the
processing.js project has changed this: you can now use your sketches directly without
turning it into an applet at all. In the same way that you include a javascript file,
or a CSS stylesheet, you can simply link to your sketch and magic happens.</p>
<p>Let's say we save the previous sketch, with the bouncing and the mouse interaction,
as "mysketch.pde", and we want to show this on a webpage. Using processing.js, this is
a trivially simple trick:</p>
{% highlight html linenos %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Processing Page</title>
<script type="text/javascript" src="processing.js"></script>
</head>
<body>
<canvas id="mysketch" data-processing-sources="mysketch.pde"></canvas>
</body>
</html>{% endhighlight %}
<canvas id="mysketch1" data-processing-sources="/sketches/mysketch.pde" style="border: 1px solid blue;"></canvas>
<div>
<span style="font-size:80%">play controls:</span>
<button type="button" onclick="stop('mysketch1')" class="Pomax">■</button>
<button type="button" onclick="play('mysketch1')" class="Pomax">▶</button>
</div>
<p>And we're done. In fact, I went ahead and made sure this page already uses processing.js,
and that there is a mysketch.pde to load. If you click on the play control for the sketch
above, it will start running, and do exactly what you would expect it to do based on what
it does when you run it from the Processing environment.</p>
<h3 id="inpage" onclick="toggleContent('inpage')">Putting a sketch inline on the page</h3>
<p>While not recommended, you can also put your sketch directly on a page, much like how
you can put javascript or CSS styles directly on a page. However, in order for processing.js
to properly load your code, you'll need some extra help in the form of the "init.js" file
that is included with the processing.js examples archive from the processing.js downloads page</p>
{% highlight html linenos %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Processing Page</title>
<script type="text/javascript" src="processing.js"></script>
</head>
<body>
<script type="application/processing" target="mysketch">
void setup() { ... }
void draw() { ... }
class SomeClass {
...
}
</script>
<canvas id="mysketch"></canvas>
</body>
</html>{% endhighlight %}
<p>There are several reasons for why this is not a very good practice, but the most important
one is that this way you can't be sure whether or not you've written a bug-free sketch. By
writing it directly on the page, you might in fact have written some buggy code, which you
will then find is terribly hard to debug because the browser is not equiped with a debugger
for Processing code. In fact, processing.js rewrites your sketch into pure javascript (using
some terribly clever tricks that we won't go into), so even if when it tells you where the
error is in a javascript debugger, it will tell you where it went wrong in the converted
javascript object, not the actual place in your source code. So keep it as a separate file,
and make sure to test your code in the Processing IDE!</p>
<h3 id="interface" onclick="toggleContent('interface')">Making your sketch and your page see each other</h3>
<p>Just running a sketch on a page is fine, but the benefit of a webpage is that it offers
the kind of user interaction that you can't get from within the sketch itself. Pretty buttons,
text areas that fold away, pop up, etc. make it very attractive to have your sketch do all
the animation graphicsy work, but have all the information about the sketch, as well as
controls for it, on the webpage. This is entirely possible - in fact, the "stop" and "play"
buttons for the sketch above are examples of javascript telling the sketch what to do. Because
a webpage offers more than a plain sketch can, processing.js has a few special tricks up its
sleeve, so that you can get the most out of your creative work. Arguably the most important of
these is the "get the sketch" function:</p>
{% highlight javascript linenos %}
var mysketch = Processing.getInstanceById('mysketchid');{% endhighlight %}
<p>This is the pivotal function on the javascript side of things. It gives you a direct reference
to your sketch, and everything in it, so that you can call any function and examine and modify
any variable that is in the sketch.</p>
<h3 id="jstosketch" onclick="toggleContent('jstosketch')">Making javascript see your sketch</h3>
<p>Let's say we have the following sketch:<p>
{% highlight java linenos %}
void setup() {
size(200,200);
noLoop(); // turn off animation, since we won't need it
stroke(#FFEE88);
fill(#FFEE88);
background(#000033);
text("",0,0); // force Processing to load a font
textSize(24); // set the font size to something big
}
void draw() { }
void drawText(String t)
{
background(#000033);
// get the width for the text
float twidth = textWidth(t);
// place the text centered on the drawing area
text(t, (width - twidth)/2, height/2);
}{% endhighlight %}
<p>We can make this sketch draw a different text based on some text we have on our webpage,
using javascript. This is in fact really easy: first, let's save this processing code as
mysketch2.pde, and load it onto a page in the same way as earlier in the article. Then, we
use javascript to ask for our sketch instance, after which we call the "drawText" function
with some text that we get from the web page that the sketch is running on:</p>
{% highlight html linenos %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Processing Page</title>
<script type="text/javascript" src="processing.js"></script>
<script type="text/javascript">
function drawSomeText(id) {
var pjs = Processing.getInstanceById(id);
var text = document.getElementById('inputtext').value;
pjs.drawText(text); }
</script>
</head>
<body>
<canvas id="mysketch2" data-processing-sources="mysketch2.pde"></canvas>
<input type="textfield" value="my text" id="inputtext">
<button type="button" onclick="drawSomeText('mysketch2')">place</button>
</body>
</html>{% endhighlight %}
<p>This has the same effect as the sketch that's running below. Simply fill in a bit
of text, and hit the ▶ button to see the sketch render it on the drawing area.</p>
<canvas id="mysketch2" data-processing-sources="/sketches/mysketch2.pde" style="border: 1px solid blue;"></canvas>
<div>
<span style="font-size:80%">set text:</span>
<input type="textfield" style="width: 6em;" value="My Text Here" id="ms2text">
<button type="button" onclick="drawText('mysketch2')" class="Pomax">▶</button>
</div>
<p>So far so good, but what if we also want to make Processing code call javascript?
In order for us to so, while making sure the sketch keeps running both on your page an
in the Processing environment, we have to do a bit more work</p>
<h3 id="sketchtojs" onclick="toggleContent('sketchtojs')">Making your sketch "see" javascript</h3>
<p>You can't just stick plain javascript in your sketch and hope everything goes well
because it's "on a web page". A better approach is to neatly separate your sketch and
your on-page javascript, and ensure that whatever you want to do on your page runs
through a javascript function. How do we do that? Let's say we have the following page:</p>
{% highlight html linenos %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Processing Page</title>
<script type="text/javascript" src="processing.js"></script>
</head>
<body>
<canvas id="mysketch3" data-processing-sources="mysketch3.pde"></canvas>
<div id="coordinates">
x/y: <input type="textfield" id="xcoord">/<input type="textfield" id="ycoord">
</div>
</body>
</html>{% endhighlight %}
<p>And say we have the following sketch, which we'll save as mysketch3.pde:</p>
{% highlight java linenos %}
void setup() {
size(200,200);
stroke(255);
background(0);
noLoop();
}
void draw() {
fill(0,0,0,40);
rect(-1,-1,width+2,height+2);
}
void mouseMoved() {
line(mouseX,0,mouseX,height);
line(0,mouseY,width,mouseY);
redraw();
}{% endhighlight %}
<p>As an exercise, let's try to get the mouse coordinates from that mouseMoved event
onto the page. This means we'll need to define a javascript function that will do this for us:</p>
{% highlight javascript linenos %}
function showXYCoordinates(x, y) {
document.getElementById('xcoord').value = x;
document.getElementById('ycoord').value = y;
}{% endhighlight %}
<p>And we'll need to make the sketch know that there is such a thing as javascript,
and that it has this function:</p>
{% highlight java linenos %}
interface JavaScript {
void showXYCoordinates(int x, int y);
}
void bindJavascript(JavaScript js) {
javascript = js;
}
JavaScript javascript;
void setup() { ...}
void draw() { ... }
void mouseMoved() {
...
if(javascript!=null){
javascript.showXYCoordinates(mouseX, mouseY);
}
}{% endhighlight %}
<p>What we've done is we've told Processing: <i>"There are things that follow the
JavaScript interface. This means that whatever else they can do, they'll have a
function called "showXYCoordinates" and that function takes two arguments, both of type int."</i>
- of course, the sketch will not magically know our on-page javascript, so we also
define a function that lets us tell the sketch what actually counts as javascript,
which is what the bindJavascript(...) function is for.</p>
<p>This leaves us with needing to make sure that we really do tell the sketch what
Javascript is, which we'll do as follows on the page:</p>
{% highlight javascript linenos %}
var bound = false;
function bindJavascript() {
var pjs = Processing.getInstanceById('mysketch3');
if(pjs!=null) {
pjs.bindJavascript(this);
bound = true;
}
if(!bound) setTimeout(bindJavascript, 250);
}
bindJavascript();{% endhighlight %}
<p>This defines a function that checks whether processing.js has loaded our sketch yet.
If not, it tries again 250ms later. If the sketch is loaded, the reference to the sketch
is used to tell it what "javascript" should be. This is achieved by virtue of processing.js
trusting that you wrote valid code. As such, as long as you're on the javascript side of
things, you can pass the sketch whatever you like, and the sketch will trust that it conforms
to what the method says the type should be. In this case we pass the javascript "this" value
(which refers to the global javascript environment for the current window), and tell processing
<i>"this thing conforms to your JavaScript interface, so it has loads of things but the only
thing you need to be concerned about is whether or not it has a showXYCoordinates(int, int)
function, which it does."</i></p>
<p>So, our final sketch behaves like the sketch below, and our final page source looks like the following:</p>
{% highlight html linenos %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Processing Page</title>
<script type="text/javascript" src="processing.js"></script>
<script type="text/javascript">
var bound = false;
function bindJavascript() {
var pjs = Processing.getInstanceById('mysketch3');
if(pjs!=null) {
pjs.bindJavascript(this);
bound = true; }
if(!bound) setTimeout(bindJavascript, 250);
}
bindJavascript();
function showXYCoordinates(x, y) {
document.getElementById('xcoord').value = x;
document.getElementById('ycoord').value = y;
}
</script>
</head>
<body>
<canvas id="mysketch3" data-processing-sources="mysketch3.pde"></canvas>
<div id="coordinates">
x/y: <input type="textfield" id="xcoord">/<input type="textfield" id="ycoord">
</div>
</body>
</html>{% endhighlight %}
<canvas id="mysketch3" data-processing-sources="/sketches/mysketch3.pde"></canvas>
<div>
x/y coordinates: <input type="textfield" id="xcoord" style="width: 3em;">/<input type="textfield" id="ycoord" style="width: 3em;">
</div>
<h3 name="jsobj" onclick="toggleContent('jsobj')">Passing complex objects from javascript to your sketch</h3>
<p>This leaves us with one last topic that we need to cover, simply because it's so common:
using an AJAX approach to get some data, and then passing that data, properly formatted, to your sketch.</p>
<h3 id="pobj" onclick="toggleContent('pobj')">Actually using Processing objects</h3>
<p>One interesting thing that processing.js allows us to do is to create objects as we defined them in
our sketch, in javascript, and then hand them over to the sketch to deal with. To give an example, let's
use the following sketch, which lets you draw points by clicking with the mouse, and links up all the
points with lines:</p>
{% highlight java linenos %}
ArrayList points;
ArrayList getPoints() { return points; }
void setup() {
size(200,200);
points = new ArrayList();
noLoop();
stroke(255,0,0);
fill(255);
}
void draw() {
background(200,200,255);
for(int p=0, end=points.size(); p < end; p++) {
Point pt = (Point) points.get(p);
if(p < end-1) {
Point next = (Point) points.get(p+1);
line(pt.x,pt.y,next.x,next.y); }
pt.draw(); }
}
void mouseClicked() {
points.add(new Point(mouseX,mouseY));
redraw();
}
class Point {
int x,y;
Point(int x, int y) { this.x=x; this.y=y; }
void draw() { ellipse(x,y,10,10); }
}{% endhighlight %}
<canvas id="mysketch4" data-processing-sources="/sketches/mysketch4.pde" style="border: 1px solid black;"></canvas>
<div>click to place points</div>
<p>We can also make javascript place some points for us, automatically, by using the following javascript:</p>
{% highlight javascript linenos %}
function loadPoints(id, button) {
var pjs = Processing.getInstanceById(id);
var points = pjs.getPoints();
points.add(new pjs.Point(10,10));
points.add(new pjs.Point(10,190));
points.add(new pjs.Point(190,190));
points.add(new pjs.Point(190,10));
pjs.draw();
}{% endhighlight %}
<canvas id="mysketch5" data-processing-sources="/sketches/mysketch5.pde" style="border: 1px solid black;"></canvas>
<div>load points: <button type="button" id="loadPoints" onclick="loadPointsJS('mysketch5', this)">load</button></div>
<p>Because processing.js turns the sketch into actual javascript, every class we defined in it
can be created using <em>new pjs.ClassName(arguments,...)</em>.</p>