-
Notifications
You must be signed in to change notification settings - Fork 0
/
p5.dom.js
2033 lines (1899 loc) · 64.1 KB
/
p5.dom.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*! p5.dom.js v0.2.6 November 24, 2015 */
/**
* <p>The web is much more than just canvas and p5.dom makes it easy to interact
* with other HTML5 objects, including text, hyperlink, image, input, video,
* audio, and webcam.</p>
* <p>There is a set of creation methods, DOM manipulation methods, and
* an extended p5.Element that supports a range of HTML elements. See the
* <a href="https://github.com/processing/p5.js/wiki/Beyond-the-canvas">
* beyond the canvas tutorial</a> for a full overview of how this addon works.
*
* <p>Methods and properties shown in black are part of the p5.js core, items in
* blue are part of the p5.dom library. You will need to include an extra file
* in order to access the blue functions. See the
* <a href="http://p5js.org/libraries/#using-a-library">using a library</a>
* section for information on how to include this library. p5.dom comes with
* <a href="http://p5js.org/download">p5 complete</a> or you can download the single file
* <a href="https://raw.githubusercontent.com/lmccart/p5.js/master/lib/addons/p5.dom.js">
* here</a>.</p>
* <p>See <a href="https://github.com/processing/p5.js/wiki/Beyond-the-canvas">tutorial: beyond the canvas</a>
* for more info on how to use this libary.</a>
*
* @module p5.dom
* @submodule p5.dom
* @for p5.dom
* @main
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd)
define('p5.dom', ['p5'], function (p5) { (factory(p5));});
else if (typeof exports === 'object')
factory(require('../p5'));
else
factory(root['p5']);
}(this, function (p5) {
// =============================================================================
// p5 additions
// =============================================================================
/**
* Searches the page for an element with the given ID, class, or tag name (using the '#' or '.'
* prefixes to specify an ID or class respectively, and none for a tag) and returns it as
* a p5.Element. If a class or tag name is given with more than 1 element,
* only the first element will be returned.
* The DOM node itself can be accessed with .elt.
* Returns null if none found. You can also specify a container to search within.
*
* @method select
* @param {String} name id, class, or tag name of element to search for
* @param {String} [container] id, p5.Element, or HTML element to search within
* @return {Object/p5.Element|Null} p5.Element containing node found
* @example
* <div ><code class='norender'>
* function setup() {
* createCanvas(100,100);
* //translates canvas 50px down
* select('canvas').translate(0,50);
* }
* </code></div>
* <div ><code class='norender'>
* // these are all valid calls to select()
* var a = select('#moo');
* var b = select('#blah', '#myContainer');
* var c = select('#foo', b);
* var d = document.getElementById('beep');
* var e = select('p', d);
* </code></div>
*
*/
p5.prototype.select = function (e, p) {
var res = null;
var container = getContainer(p);
if (e[0] === '.'){
e = e.slice(1);
res = container.getElementsByClassName(e);
if (res.length) {
res = res[0];
} else {
res = null;
}
}else if (e[0] === '#'){
e = e.slice(1);
res = container.getElementById(e);
}else {
res = container.getElementsByTagName(e);
if (res.length) {
res = res[0];
} else {
res = null;
}
}
if (res) {
return wrapElement(res);
} else {
return null;
}
};
/**
* Searches the page for elements with the given class or tag name (using the '.' prefix
* to specify a class and no prefix for a tag) and returns them as p5.Elements
* in an array.
* The DOM node itself can be accessed with .elt.
* Returns an empty array if none found.
* You can also specify a container to search within.
*
* @method selectAll
* @param {String} name class or tag name of elements to search for
* @param {String} [container] id, p5.Element, or HTML element to search within
* @return {Array} Array of p5.Elements containing nodes found
* @example
* <div ><code class='norender'>
* function setup() {
* createButton('btn');
* createButton('2nd btn');
* createButton('3rd btn');
* var buttons = selectAll('button');
*
* for (var i = 0; i < buttons.length; i++){
* buttons[i].size(100,100);
* }
* }
* </code></div>
* <div ><code class='norender'>
* // these are all valid calls to selectAll()
* var a = selectAll('.moo');
* var b = selectAll('div');
* var c = selectAll('button', '#myContainer');
* var d = select('#container');
* var e = selectAll('p', d);
* var f = document.getElementById('beep');
* var g = select('.blah', f);
* </code></div>
*
*/
p5.prototype.selectAll = function (e, p) {
var arr = [];
var res;
var container = getContainer(p);
if (e[0] === '.'){
e = e.slice(1);
res = container.getElementsByClassName(e);
} else {
res = container.getElementsByTagName(e);
}
if (res) {
for (var j = 0; j < res.length; j++) {
var obj = wrapElement(res[j]);
arr.push(obj);
}
}
return arr;
};
/**
* Helper function for select and selectAll
*/
function getContainer(p) {
var container = document;
if (typeof p === 'string' && p[0] === '#'){
p = p.slice(1);
container = document.getElementById(p) || document;
} else if (p instanceof p5.Element){
container = p.elt;
} else if (p instanceof HTMLElement){
container = p;
}
return container;
}
/**
* Helper function for getElement and getElements.
*/
function wrapElement(elt) {
if(elt.tagName === "INPUT" && elt.type === "checkbox") {
var converted = new p5.Element(elt);
converted.checked = function(){
if (arguments.length === 0){
return this.elt.checked;
} else if(arguments[0]) {
this.elt.checked = true;
} else {
this.elt.checked = false;
}
return this;
};
return converted;
} else if (elt.tagName === "VIDEO" || elt.tagName === "AUDIO") {
return new p5.MediaElement(elt);
} else {
return new p5.Element(elt);
}
}
/**
* Removes all elements created by p5, except any canvas / graphics
* elements created by createCanvas or createGraphics.
* Event handlers are removed, and element is removed from the DOM.
* @method removeElements
* @example
* <div class='norender'><code>
* function setup() {
* createCanvas(100, 100);
* createDiv('this is some text');
* createP('this is a paragraph');
* }
* function mousePressed() {
* removeElements(); // this will remove the div and p, not canvas
* }
* </code></div>
*
*/
p5.prototype.removeElements = function (e) {
for (var i=0; i<this._elements.length; i++) {
if (!(this._elements[i].elt instanceof HTMLCanvasElement)) {
this._elements[i].remove();
}
}
};
/**
* Helpers for create methods.
*/
function addElement(elt, pInst, media) {
var node = pInst._userNode ? pInst._userNode : document.body;
node.appendChild(elt);
var c = media ? new p5.MediaElement(elt) : new p5.Element(elt);
pInst._elements.push(c);
return c;
}
/**
* Creates a <div></div> element in the DOM with given inner HTML.
* Appends to the container node if one is specified, otherwise
* appends to body.
*
* @method createDiv
* @param {String} html inner HTML for element created
* @return {Object/p5.Element} pointer to p5.Element holding created node
* @example
* <div class='norender'><code>
* var myDiv;
* function setup() {
* myDiv = createDiv('this is some text');
* }
* </code></div>
*/
/**
* Creates a <p></p> element in the DOM with given inner HTML. Used
* for paragraph length text.
* Appends to the container node if one is specified, otherwise
* appends to body.
*
* @method createP
* @param {String} html inner HTML for element created
* @return {Object/p5.Element} pointer to p5.Element holding created node
* @example
* <div class='norender'><code>
* var myP;
* function setup() {
* myP = createP('this is some text');
* }
* </code></div>
*/
/**
* Creates a <span></span> element in the DOM with given inner HTML.
* Appends to the container node if one is specified, otherwise
* appends to body.
*
* @method createSpan
* @param {String} html inner HTML for element created
* @return {Object/p5.Element} pointer to p5.Element holding created node
* @example
* <div class='norender'><code>
* var mySpan;
* function setup() {
* mySpan = createSpan('this is some text');
* }
* </code></div>
*/
var tags = ['div', 'p', 'span'];
tags.forEach(function(tag) {
var method = 'create' + tag.charAt(0).toUpperCase() + tag.slice(1);
p5.prototype[method] = function(html) {
var elt = document.createElement(tag);
elt.innerHTML = typeof html === undefined ? "" : html;
return addElement(elt, this);
}
});
/**
* Creates an <img /> element in the DOM with given src and
* alternate text.
* Appends to the container node if one is specified, otherwise
* appends to body.
*
* @method createImg
* @param {String} src src path or url for image
* @param {String} [alt] alternate text to be used if image does not load
* @param {Function} [successCallback] callback to be called once image data is loaded
* @return {Object/p5.Element} pointer to p5.Element holding created node
* @example
* <div class='norender'><code>
* var img;
* function setup() {
* img = createImg('http://p5js.org/img/asterisk-01.png');
* }
* </code></div>
*/
p5.prototype.createImg = function() {
var elt = document.createElement('img');
var args = arguments;
var self;
var setAttrs = function(){
self.width = elt.offsetWidth;
self.height = elt.offsetHeight;
if (args.length > 1 && typeof args[1] === 'function'){
self.fn = args[1];
self.fn();
}else if (args.length > 1 && typeof args[2] === 'function'){
self.fn = args[2];
self.fn();
}
};
elt.src = args[0];
if (args.length > 1 && typeof args[1] === 'string'){
elt.alt = args[1];
}
elt.onload = function(){
setAttrs();
}
self = addElement(elt, this);
return self;
};
/**
* Creates an <a></a> element in the DOM for including a hyperlink.
* Appends to the container node if one is specified, otherwise
* appends to body.
*
* @method createA
* @param {String} href url of page to link to
* @param {String} html inner html of link element to display
* @param {String} [target] target where new link should open,
* could be _blank, _self, _parent, _top.
* @return {Object/p5.Element} pointer to p5.Element holding created node
* @example
* <div class='norender'><code>
* var myLink;
* function setup() {
* myLink = createA('http://p5js.org/', 'this is a link');
* }
* </code></div>
*/
p5.prototype.createA = function(href, html, target) {
var elt = document.createElement('a');
elt.href = href;
elt.innerHTML = html;
if (target) elt.target = target;
return addElement(elt, this);
};
/** INPUT **/
/**
* Creates a slider <input></input> element in the DOM.
* Use .size() to set the display length of the slider.
* Appends to the container node if one is specified, otherwise
* appends to body.
*
* @method createSlider
* @param {Number} min minimum value of the slider
* @param {Number} max maximum value of the slider
* @param {Number} [value] default value of the slider
* @return {Object/p5.Element} pointer to p5.Element holding created node
* @example
* <div><code>
* var slider;
* function setup() {
* slider = createSlider(0, 255, 100);
* slider.position(10, 10);
* slider.style('width', '80px');
* }
*
* function draw() {
* var val = slider.value();
* background(val);
* }
* </code></div>
*/
p5.prototype.createSlider = function(min, max, value, step) {
var elt = document.createElement('input');
elt.type = 'range';
elt.min = min;
elt.max = max;
if (step) elt.step = step;
if (typeof(value) === "number") elt.value = value;
return addElement(elt, this);
};
/**
* Creates a <button></button> element in the DOM.
* Use .size() to set the display size of the button.
* Use .mousePressed() to specify behavior on press.
* Appends to the container node if one is specified, otherwise
* appends to body.
*
* @method createButton
* @param {String} label label displayed on the button
* @param {String} [value] value of the button
* @return {Object/p5.Element} pointer to p5.Element holding created node
* @example
* <div class='norender'><code>
* var button;
* function setup() {
* createCanvas(100, 100);
* background(0);
* button = createButton('click me');
* button.position(19, 19);
* button.mousePressed(changeBG);
* }
*
* function changeBG() {
* var val = random(255);
* background(val);
* }
* </code></div>
*/
p5.prototype.createButton = function(label, value) {
var elt = document.createElement('button');
elt.innerHTML = label;
elt.value = value;
if (value) elt.value = value;
return addElement(elt, this);
};
/**
* Creates a checkbox <input></input> element in the DOM.
* Calling .checked() on a checkbox returns if it is checked or not
*
* @method createCheckbox
* @param {String} [label] label displayed after checkbox
* @param {boolean} [value] value of the checkbox; checked is true, unchecked is false.Unchecked if no value given
* @return {Object/p5.Element} pointer to p5.Element holding created node
* @example
* <div class='norender'><code>
* var checkbox;
*
* function setup() {
* checkbox = createCheckbox('label', false);
* checkbox.changed(myCheckedEvent);
* }
*
* function myCheckedEvent() {
* if (this.checked()) {
* console.log("Unchecking!");
* } else {
* console.log("Checking!");
* }
*
* </code></div>
*/
p5.prototype.createCheckbox = function() {
var elt = document.createElement('input');
elt.type = 'checkbox';
//checkbox must be wrapped in p5.Element before label so that label appears after
var self = addElement(elt, this);
self.checked = function(){
if (arguments.length === 0){
return self.elt.checked;
}else if(arguments[0]){
self.elt.checked = true;
}else{
self.elt.checked = false;
}
return self;
};
this.value = function(val){
self.value = val;
return this;
};
if (arguments[0]){
var ran = Math.random().toString(36).slice(2);
var label = document.createElement('label');
elt.setAttribute('id', ran);
label.htmlFor = ran;
self.value(arguments[0]);
label.appendChild(document.createTextNode(arguments[0]));
addElement(label, this);
}
if (arguments[1]){
elt.checked = true;
}
return self;
};
/**
* Creates a dropdown menu <select></select> element in the DOM.
* @method createSelect
* @param {boolean} [multiple] [true if dropdown should support multiple selections]
* @return {Object/p5.Element} pointer to p5.Element holding created node
* @example
* <div><code>
* var sel;
*
* function setup() {
* textAlign(CENTER);
* background(200);
* sel = createSelect();
* sel.position(10, 10);
* sel.option('pear');
* sel.option('kiwi');
* sel.option('grape');
* sel.changed(mySelectEvent);
* }
*
* function mySelectEvent() {
* var item = sel.value();
* background(200);
* text("it's a "+item+"!", 50, 50);
* }
* </code></div>
*/
p5.prototype.createSelect = function(mult) {
var elt = document.createElement('select');
if (mult){
elt.setAttribute('multiple', 'true');
}
var self = addElement(elt, this);
self.option = function(name, value){
var opt = document.createElement('option');
opt.innerHTML = name;
if (arguments.length > 1)
opt.value = value;
else
opt.value = name;
elt.appendChild(opt);
};
self.selected = function(value){
var arr = [];
if (arguments.length > 0){
for (var i = 0; i < this.elt.length; i++){
if (value.toString() === this.elt[i].value){
this.elt.selectedIndex = i;
}
}
return this;
}else{
if (mult){
for (var i = 0; i < this.elt.selectedOptions.length; i++){
arr.push(this.elt.selectedOptions[i].value);
}
return arr;
}else{
return this.elt.value;
}
}
};
return self;
};
/**
* Creates a radio button <input></input> element in the DOM.
*
* @method createRadio
* @param {String} [divId] the id and name of the created div and input field respectively
* @return {Object/p5.Element} pointer to p5.Element holding created node
*/
p5.prototype.createRadio = function() {
var radios = document.querySelectorAll("input[type=radio]");
var count = 0;
if(radios.length > 1){
console.log(radios,radios[0].name);
var length = radios.length;
var prev=radios[0].name;
var current = radios[1].name;
count=1;
for(var i = 1; i < length; i++ ){
current = radios[i].name;
if(prev != current){
count++;
}
prev = current;
}
}
else if (radios.length == 1){
count = 1;
}
var elt = document.createElement('div');
var self = addElement(elt, this);
var times = -1;
self.option = function(name, value){
var opt = document.createElement('input');
opt.type = 'radio';
opt.innerHTML = name;
if (arguments.length > 1)
opt.value = value;
else
opt.value = name;
opt.setAttribute('name',"defaultradio"+count);
elt.appendChild(opt);
if (name){
times++;
var ran = Math.random().toString(36).slice(2);
var label = document.createElement('label');
opt.setAttribute('id', "defaultradio"+count+"-"+times);
label.htmlFor = "defaultradio"+count+"-"+times;
label.appendChild(document.createTextNode(name));
elt.appendChild(label);
}
return opt;
};
self.selected = function(){
var length = this.elt.childNodes.length;
if(arguments[0]) {
for (var i = 0; i < length; i+=2){
if(this.elt.childNodes[i].value == arguments[0])
this.elt.childNodes[i].checked = true;
}
return this;
} else {
for (var i = 0; i < length; i+=2){
if(this.elt.childNodes[i].checked == true)
return this.elt.childNodes[i].value;
}
}
};
self.value = function(){
var length = this.elt.childNodes.length;
if(arguments[0]) {
for (var i = 0; i < length; i+=2){
if(this.elt.childNodes[i].value == arguments[0])
this.elt.childNodes[i].checked = true;
}
return this;
} else {
for (var i = 0; i < length; i+=2){
if(this.elt.childNodes[i].checked == true)
return this.elt.childNodes[i].value;
}
return "";
}
};
return self
};
/**
* Creates an <input></input> element in the DOM for text input.
* Use .size() to set the display length of the box.
* Appends to the container node if one is specified, otherwise
* appends to body.
*
* @method createInput
* @param {Number} [value] default value of the input box
* @return {Object/p5.Element} pointer to p5.Element holding created node
* @example
* <div class='norender'><code>
* function setup(){
* var inp = createInput('');
* inp.input(myInputEvent);
* }
*
* function myInputEvent(){
* console.log('you are typing: ', this.value());
* }
*
* </code></div>
*/
p5.prototype.createInput = function(value) {
var elt = document.createElement('input');
elt.type = 'text';
if (value) elt.value = value;
return addElement(elt, this);
};
/**
* Creates an <input></input> element in the DOM of type 'file'.
* This allows users to select local files for use in a sketch.
*
* @method createFileInput
* @param {Function} [callback] callback function for when a file loaded
* @param {String} [multiple] optional to allow multiple files selected
* @return {Object/p5.Element} pointer to p5.Element holding created DOM element
*/
p5.prototype.createFileInput = function(callback, multiple) {
// Is the file stuff supported?
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Yup, we're ok and make an input file selector
var elt = document.createElement('input');
elt.type = 'file';
// If we get a second argument that evaluates to true
// then we are looking for multiple files
if (multiple) {
// Anything gets the job done
elt.multiple = 'multiple';
}
// Function to handle when a file is selected
// We're simplifying life and assuming that we always
// want to load every selected file
function handleFileSelect(evt) {
// These are the files
var files = evt.target.files;
// Load each one and trigger a callback
for (var i = 0; i < files.length; i++) {
var f = files[i];
var reader = new FileReader();
function makeLoader(theFile) {
// Making a p5.File object
var p5file = new p5.File(theFile);
return function(e) {
p5file.data = e.target.result;
callback(p5file);
};
};
reader.onload = makeLoader(f);
// Text or data?
// This should likely be improved
if (f.type.indexOf('text') > -1) {
reader.readAsText(f);
} else {
reader.readAsDataURL(f);
}
}
}
// Now let's handle when a file was selected
elt.addEventListener('change', handleFileSelect, false);
return addElement(elt, this);
} else {
console.log('The File APIs are not fully supported in this browser. Cannot create element.');
}
};
/** VIDEO STUFF **/
function createMedia(pInst, type, src, callback) {
var elt = document.createElement(type);
// allow src to be empty
var src = src || '';
if (typeof src === 'string') {
src = [src];
}
for (var i=0; i<src.length; i++) {
var source = document.createElement('source');
source.src = src[i];
elt.appendChild(source);
}
if (typeof callback !== 'undefined') {
var callbackHandler = function() {
callback();
elt.removeEventListener('canplaythrough', callbackHandler);
}
elt.addEventListener('canplaythrough', callbackHandler);
}
var c = addElement(elt, pInst, true);
c.loadedmetadata = false;
// set width and height onload metadata
elt.addEventListener('loadedmetadata', function() {
c.width = elt.videoWidth;
c.height = elt.videoHeight;
c.loadedmetadata = true;
});
return c;
}
/**
* Creates an HTML5 <video> element in the DOM for simple playback
* of audio/video. Shown by default, can be hidden with .hide()
* and drawn into canvas using video(). Appends to the container
* node if one is specified, otherwise appends to body. The first parameter
* can be either a single string path to a video file, or an array of string
* paths to different formats of the same video. This is useful for ensuring
* that your video can play across different browsers, as each supports
* different formats. See <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats">this
* page</a> for further information about supported formats.
*
* @method createVideo
* @param {String|Array} src path to a video file, or array of paths for
* supporting different browsers
* @param {Object} [callback] callback function to be called upon
* 'canplaythrough' event fire, that is, when the
* browser can play the media, and estimates that
* enough data has been loaded to play the media
* up to its end without having to stop for
* further buffering of content
* @return {Object/p5.Element} pointer to video p5.Element
*/
p5.prototype.createVideo = function(src, callback) {
return createMedia(this, 'video', src, callback);
};
/** AUDIO STUFF **/
/**
* Creates a hidden HTML5 <audio> element in the DOM for simple audio
* playback. Appends to the container node if one is specified,
* otherwise appends to body. The first parameter
* can be either a single string path to a audio file, or an array of string
* paths to different formats of the same audio. This is useful for ensuring
* that your audio can play across different browsers, as each supports
* different formats. See <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats">this
* page for further information about supported formats.
*
* @method createAudio
* @param {String|Array} src path to an audio file, or array of paths for
* supporting different browsers
* @param {Object} [callback] callback function to be called upon
* 'canplaythrough' event fire, that is, when the
* browser can play the media, and estimates that
* enough data has been loaded to play the media
* up to its end without having to stop for
* further buffering of content
* @return {Object/p5.Element} pointer to audio p5.Element
*/
p5.prototype.createAudio = function(src, callback) {
return createMedia(this, 'audio', src, callback);
};
/** CAMERA STUFF **/
p5.prototype.VIDEO = 'video';
p5.prototype.AUDIO = 'audio';
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
/**
* Creates a new <video> element that contains the audio/video feed
* from a webcam. This can be drawn onto the canvas using video(). More
* specific properties of the stream can be passing in a Constraints object.
* See the
* <a href="http://w3c.github.io/mediacapture-main/getusermedia.html">W3C
* spec</a> for possible properties. Note that not all of these are supported
* by all browsers.
*
* @method createCapture
* @param {String|Constant|Object} type type of capture, either VIDEO or
* AUDIO if none specified, default both,
* or a Constraints boject
* @param {Function} callback function to be called once
* stream has loaded
* @return {Object/p5.Element} capture video p5.Element
* @example
* <div class='norender'><code>
* var capture;
*
* function setup() {
* createCanvas(480, 120);
* capture = createCapture(VIDEO);
* }
*
* function draw() {
* image(capture, 0, 0, width, width*capture.height/capture.width);
* filter(INVERT);
* }
* </code></div>
* <div class='norender'><code>
* function setup() {
* createCanvas(480, 120);
* var constraints = {
* video: {
* mandatory: {
* minWidth: 1280,
* minHeight: 720
* },
* optional: [
* { maxFrameRate: 10 }
* ]
* },
* audio: true
* };
* createCapture(constraints, function(stream) {
* console.log(stream);
* });
* }
* </code></div>
*/
p5.prototype.createCapture = function() {
var useVideo = true;
var useAudio = true;
var constraints;
var cb;
for (var i=0; i<arguments.length; i++) {
if (arguments[i] === p5.prototype.VIDEO) {
useAudio = false;
} else if (arguments[i] === p5.prototype.AUDIO) {
useVideo = false;
} else if (typeof arguments[i] === 'object') {
constraints = arguments[i];
} else if (typeof arguments[i] === 'function') {
cb = arguments[i];
}
}
if (navigator.getUserMedia) {
var elt = document.createElement('video');
if (!constraints) {
constraints = {video: useVideo, audio: useAudio};
}
navigator.getUserMedia(constraints, function(stream) {
elt.src = window.URL.createObjectURL(stream);
elt.onloadedmetadata = function(e) {
elt.play();
if (cb) {
cb(stream);
}
};
}, function(e) { console.log(e); });
} else {
throw 'getUserMedia not supported in this browser';
}
var c = addElement(elt, this, true);
c.loadedmetadata = false;
// set width and height onload metadata
elt.addEventListener('loadedmetadata', function() {
c.width = elt.videoWidth;
c.height = elt.videoHeight;
c.loadedmetadata = true;
});
return c;
};
/**
* Creates element with given tag in the DOM with given content.
* Appends to the container node if one is specified, otherwise
* appends to body.
*
* @method createElement
* @param {String} tag tag for the new element
* @param {String} [content] html content to be inserted into the element
* @return {Object/p5.Element} pointer to p5.Element holding created node
* @example
* <div class='norender'><code>
* var h2 = createElement('h2','im an h2 p5.element!');
* </code></div>
*/
p5.prototype.createElement = function(tag, content) {
var elt = document.createElement(tag);
if (typeof content !== 'undefined') {
elt.innerHTML = content;
}
return addElement(elt, this);
};
// =============================================================================
// p5.Element additions
// =============================================================================
/**
*
* Adds specified class to the element.
*
* @for p5.Element
* @method addClass
* @param {String} class name of class to add
* @return {Object/p5.Element}
* @example
* <div class='norender'><code>
* var div = createDiv('div');
* div.addClass('myClass');
* </code></div>
*/
p5.Element.prototype.addClass = function(c) {
if (this.elt.className) {
// PEND don't add class more than once
//var regex = new RegExp('[^a-zA-Z\d:]?'+c+'[^a-zA-Z\d:]?');
//if (this.elt.className.search(/[^a-zA-Z\d:]?hi[^a-zA-Z\d:]?/) === -1) {
this.elt.className = this.elt.className+' '+c;
//}
} else {
this.elt.className = c;
}
return this;
}
/**
*
* Removes specified class from the element.
*
* @method removeClass
* @param {String} class name of class to remove
* @return {Object/p5.Element}
*/
p5.Element.prototype.removeClass = function(c) {
var regex = new RegExp('(?:^|\\s)'+c+'(?!\\S)');