├── LICENSE
├── README.md
├── blog_post.md
├── blog_post.pdf
├── index.html
└── static
├── NN_viz.js
├── p5.dom.js
└── p5.min.js
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
341 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # NN_viz
2 | For FFL Blog
3 |
--------------------------------------------------------------------------------
/blog_post.md:
--------------------------------------------------------------------------------
1 | # What is "Learning" for Neural Networks
2 |
3 | Neural networks have spurred a lot of excitement recently. They are quickly proving to be one of the most promising and practical implementations of AI within technological systems. At Fast Forward Labs, we've been researching and building systems that use neural networks for object recognition in images. You may have seen our prototype [pictograph](www.pictograph.us). Our goal has been to really understand this technology both technically and in terms of impact and possibility.
4 |
5 | As it turns out, these systems are *extremely* difficult to understand due to their complexity. You may have run into one of Google's efforts to make sense of neural networks through their [research blog](http://googleresearch.blogspot.ch/2015/06/inceptionism-going-deeper-into-neural.html) or their [explanatory videos](https://www.youtube.com/watch?v=bHvf7Tagt18&index=11&list=PLeqAcoTy5741GXa8rccolGQaj_nVGw76g).
6 |
7 | ## Nature of this post
8 |
9 | This post is an extension of this effort to improve how we understand neural networks, specifically around how they "learn".
10 |
11 | Let's start with two points brought home by the team at Google in the above posts:
12 |
13 | 1. Neural networks are difficult to interpret so we have to develop specific techniques to gain insight on what they are doing.
14 | 2. Certain learning tasks us humans do are *very* hard to achieve in artificial neural networks.
15 |
16 | In relation to these points, what I've built is a detailed visualization of how a neural network functions at neuron-by-neuron level, and also how it "learns". If you're already familiar with neural networks or want to follow the rest of the post with a visual cue, please see the visualization [here](http://mwskirpan.com/NN_viz)
17 |
18 | ## Neural Network Basics
19 |
20 | Let's first be sure that we're all on the same page about neural networks basics. Neural networks are composed of layers of computational units (neurons) where each neuron in a layer is connected to each neuron in the next layer. We pass data (e.g., pixel values in an image, words in a text) into our input layer, then many hidden layers transform this data until the output layer makes a prediction or classification on the original data.
21 |
22 | How this "transformation" works is that each neuron passes along a value to the next neuron. During this passing, we multiply the value by some **weight**, sum it up with all the other values incoming to the same neuron, adjust it by the neuron's **bias**, and finally pass it through an **activation function** which normalizes the output. This somewhat simple process is done over and over until finally our output layer has some *scores* or *predictions*.
23 |
24 | Now to the learning.
25 |
26 | These predictions are then compared to some **target**, or correct answer. We then use a **cost function** to determine how much we want to *punish* each of our guesses given how much they strayed from our target values. We then use this information to **backpropagate** across all our neurons and connections in order to adjust the biases and weights.
27 |
28 | And this is it, *backpropagation* is how a neural network learns a particular task.
29 |
30 | ## Details of the Visualization
31 |
32 | At this point it may be worth to go ahead and play with the visualization a bit to see these components at work. What you'll notice is that I have given you the ability to adjust the inputs, each connection has the value of its weight hovering nearby, and each neuron has its bias (b) below and the result of its activation function $\sigma$ above.
33 |
34 | When you click `forward` you can see the final layers guesses in comparison to the target values. Then when you click `backprop` you can watch as the values are adjusted minutely. Then when you press `forward` again, you should see the the output layer improve slightly in comparison to the targets.
35 |
36 | For those AI engineers out there, you'll notice there are certain complications we've ignored for the purpose of exposition. Right now, I use a [softmax function](https://en.wikipedia.org/wiki/Softmax_function) to compute our cost, and a [sigmoid function](https://en.wikipedia.org/wiki/Sigmoid_function) for activation. We have ignored other aspects of normal training like regularization, dropout, and mini-batching.
37 |
38 | The trade-off being that, with less features to pay attention to, we can hone in on understanding the fundamentals involved in this procedure.
39 |
40 | ## Interpreting Learning
41 |
42 | With some background laid and the visualization explained, let's move on to talk about learning. The first thing to notice is, even in this simple network, paying attention to one particular number does not tell us much about how the entire system behaves. In fact, this is one of the reasons neural networks are hard to interpret: inspecting specific numbers in our system gives us little to no information about the overall dynamics.
43 |
44 | So, when we think about learning, we don't want to get too invested in the meaning of tweaking each parameter. While this *is* the process, it's hard to see why this amounts to learning. Instead, we want to think about this in terms of **emergence**. That is, complex systems often run on simple rules, and those simple rules compound to create **emergent behaviors**. [Conway's game of life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) is a great example of this, where we can see complicated structures form by just turning cells in a grid on and off according to a few basic rules.
45 |
46 | Much like our brains, we cannot find our entire answer by looking at one particular region. Rather, we must try to make sense of how the different functional pieces give us the gestalt phenomenon of conscious thinking (which of course we are still struggling to understand).
47 |
48 | Why we need to be careful to compare neural networks to brains is that brains have much more going on than these computational processes. Each time you train a neural network, you do so against a specific, singular task. Human learning, on the other hand, involves switching across contexts and redefining your task as you go along. At the physical level, our brains do not merely *adjust* their connections, but there chemical, electrical, and even quantum effects that determine how we rewire our brains and then act toward goals.
49 |
50 | Having put these exceptions out in the open, we can still leverage the brain metaphor to understand our neural network's learning process. Feeding information forward, to us, is akin to receiving a new visual or tactile input and our brain processing this stimulus. Evaluating the cost function is the neural net's version of us evaluating a stimulus and determining the correct response. Finally, backpropagation is like the network reflecting on its errors so it can do better next time.
51 |
52 | Given this learning mechanism, it's still unclear to us what kind of intelligence we'll see emerge from these systems in the coming years. However, it is important we all develop a realistic understanding in order to not over-aggrandize or under-anticipate what may be possible.
53 |
54 | Hopefully using [my visualization](http://mwskirpan.com/NN_viz) and this accompanying explanation we have a clearer picture of what "learning" really means. Getting our heads around the new systems we create is difficult, but also important for education, public communication, and choices around how to engineer systems with realistic expectations.
--------------------------------------------------------------------------------
/blog_post.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wannabeCitizen/NN_viz/15fc8cef76937b3befc9d7841c04279f34055f79/blog_post.pdf
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
There is a set of creation methods, DOM manipulation methods, and
7 | * an extended p5.Element that supports a range of HTML elements. See the
8 | *
9 | * beyond the canvas tutorial for a full overview of how this addon works.
10 | *
11 | *
Methods and properties shown in black are part of the p5.js core, items in
12 | * blue are part of the p5.dom library. You will need to include an extra file
13 | * in order to access the blue functions. See the
14 | * using a library
15 | * section for information on how to include this library. p5.dom comes with
16 | * p5 complete or you can download the single file
17 | *
18 | * here.
19 | *
See tutorial: beyond the canvas
20 | * for more info on how to use this libary.
21 | *
22 | * @module p5.dom
23 | * @submodule p5.dom
24 | * @for p5.dom
25 | * @main
26 | */
27 |
28 | (function (root, factory) {
29 | if (typeof define === 'function' && define.amd)
30 | define('p5.dom', ['p5'], function (p5) { (factory(p5));});
31 | else if (typeof exports === 'object')
32 | factory(require('../p5'));
33 | else
34 | factory(root['p5']);
35 | }(this, function (p5) {
36 | // =============================================================================
37 | // p5 additions
38 | // =============================================================================
39 |
40 | /**
41 | * Searches the page for an element with the given ID, class, or tag name (using the '#' or '.'
42 | * prefixes to specify an ID or class respectively, and none for a tag) and returns it as
43 | * a p5.Element. If a class or tag name is given with more than 1 element,
44 | * only the first element will be returned.
45 | * The DOM node itself can be accessed with .elt.
46 | * Returns null if none found.
47 | *
48 | * @method select
49 | * @param {String} name id, class, or tag name of element to search for
50 | * @return {Object/p5.Element|Null} p5.Element containing node found
51 | */
52 | p5.prototype.select = function (e) {
53 | var res;
54 | var str;
55 | if (e[0] === '.'){
56 | str = e.slice(1);
57 | res = document.getElementsByClassName(str);
58 | if (res) {
59 | return wrapElement(res[0]);
60 | }else {
61 | return null;
62 | }
63 | }else if (e[0] === '#'){
64 | str = e.slice(1);
65 | res = document.getElementById(str);
66 | if (res) {
67 | return wrapElement(res);
68 | }else {
69 | return null;
70 | }
71 | }else{
72 | res = document.getElementsByTagName(e);
73 | if (res) {
74 | return wrapElement(res[0]);
75 | }else {
76 | return null;
77 | }
78 | }
79 | };
80 |
81 | /**
82 | * Searches the page for elements with the given class or tag name (using the '.' prefix
83 | * to specify a class and no prefix for a tag) and returns them as p5.Elements
84 | * in an array.
85 | * The DOM node itself can be accessed with .elt.
86 | * Returns null if none found.
87 | *
88 | * @method selectAll
89 | * @param {String} name class or tag name of elements to search for
90 | * @return {Array} Array of p5.Elements containing nodes found
91 | */
92 | p5.prototype.selectAll = function (e) {
93 | var arr = [];
94 | var res;
95 | var str;
96 | if (e[0] === '.'){
97 | str = e.slice(1);
98 | res = document.getElementsByClassName(str);
99 | }else {
100 | res = document.getElementsByTagName(e);
101 | }
102 | if (res) {
103 | for (var j = 0; j < res.length; j++) {
104 | var obj = wrapElement(res[j]);
105 | arr.push(obj);
106 | }
107 | }
108 | return arr;
109 | };
110 |
111 | /**
112 | * Helper function for getElement and getElements.
113 | */
114 | function wrapElement(elt) {
115 | if (elt.tagName === "VIDEO" || elt.tagName === "AUDIO") {
116 | return new p5.MediaElement(elt);
117 | } else {
118 | return new p5.Element(elt);
119 | }
120 | }
121 |
122 | /**
123 | * Removes all elements created by p5, except any canvas / graphics
124 | * elements created by createCanvas or createGraphics.
125 | * Event handlers are removed, and element is removed from the DOM.
126 | * @method removeElements
127 | * @example
128 | *
129 | * function setup() {
130 | * createCanvas(100, 100);
131 | * createDiv('this is some text');
132 | * createP('this is a paragraph');
133 | * }
134 | * function mousePressed() {
135 | * removeElements(); // this will remove the div and p, not canvas
136 | * }
137 | *
138 | *
139 | */
140 | p5.prototype.removeElements = function (e) {
141 | for (var i=0; i 1 && typeof args[1] === 'string'){
225 | elt.alt = args[1];
226 | }
227 | if (elt.complete){
228 | setAttrs();
229 | }else{
230 | elt.onload = function(){
231 | setAttrs();
232 | }
233 | }
234 | self = addElement(elt, this);
235 | return self;
236 | };
237 |
238 | /**
239 | * Creates an <a></a> element in the DOM for including a hyperlink.
240 | * Appends to the container node if one is specified, otherwise
241 | * appends to body.
242 | *
243 | * @method createA
244 | * @param {String} href url of page to link to
245 | * @param {String} html inner html of link element to display
246 | * @param {String} [target] target where new link should open,
247 | * could be _blank, _self, _parent, _top.
248 | * @return {Object/p5.Element} pointer to p5.Element holding created node
249 | */
250 | p5.prototype.createA = function(href, html, target) {
251 | var elt = document.createElement('a');
252 | elt.href = href;
253 | elt.innerHTML = html;
254 | if (target) elt.target = target;
255 | return addElement(elt, this);
256 | };
257 |
258 | /** INPUT **/
259 |
260 |
261 | /**
262 | * Creates a slider <input></input> element in the DOM.
263 | * Use .size() to set the display length of the slider.
264 | * Appends to the container node if one is specified, otherwise
265 | * appends to body.
266 | *
267 | * @method createSlider
268 | * @param {Number} min minimum value of the slider
269 | * @param {Number} max maximum value of the slider
270 | * @param {Number} [value] default value of the slider
271 | * @return {Object/p5.Element} pointer to p5.Element holding created node
272 | */
273 | p5.prototype.createSlider = function(min, max, value, step) {
274 | var elt = document.createElement('input');
275 | elt.type = 'range';
276 | elt.min = min;
277 | elt.max = max;
278 | if (step) elt.step = step;
279 | if (value) elt.value = value;
280 | return addElement(elt, this);
281 | };
282 |
283 | /**
284 | * Creates a <button></button> element in the DOM.
285 | * Use .size() to set the display size of the button.
286 | * Use .mousePressed() to specify behavior on press.
287 | * Appends to the container node if one is specified, otherwise
288 | * appends to body.
289 | *
290 | * @method createButton
291 | * @param {String} label label displayed on the button
292 | * @param {String} [value] value of the button
293 | * @return {Object/p5.Element} pointer to p5.Element holding created node
294 | */
295 | p5.prototype.createButton = function(label, value) {
296 | var elt = document.createElement('button');
297 | elt.innerHTML = label;
298 | elt.value = value;
299 | if (value) elt.value = value;
300 | return addElement(elt, this);
301 | };
302 |
303 | /**
304 | * Creates a checkbox <input></input> element in the DOM.
305 | *
306 | * @method createCheckbox
307 | * @param {String} [label] label displayed after checkbox
308 | * @param {boolean} [value] value of the checkbox; checked is true, unchecked is false. Unchecked if no value given
309 | * @return {Object/p5.Element} pointer to p5.Element holding created node
310 | */
311 | p5.prototype.createCheckbox = function() {
312 | var elt = document.createElement('input');
313 | elt.type = 'checkbox';
314 | //checkbox must be wrapped in p5.Element before label so that label appears after
315 | var self = addElement(elt, this);
316 | self.checked = function(){
317 | if (arguments.length === 0){
318 | return self.elt.checked;
319 | }else if(arguments[0]){
320 | self.elt.checked = true;
321 | }else{
322 | self.elt.checked = false;
323 | }
324 | return self;
325 | };
326 | this.value = function(val){
327 | self.value = val;
328 | return this;
329 | };
330 | if (arguments[0]){
331 | var ran = Math.random().toString(36).slice(2);
332 | var label = document.createElement('label');
333 | elt.setAttribute('id', ran);
334 | label.htmlFor = ran;
335 | self.value(arguments[0]);
336 | label.appendChild(document.createTextNode(arguments[0]));
337 | addElement(label, this);
338 | }
339 | if (arguments[1]){
340 | elt.checked = true;
341 | }
342 | return self;
343 | };
344 |
345 | /**
346 | * Creates a dropdown menu <select></select> element in the DOM.
347 | * @method createSelect
348 | * @param {boolean} [multiple] [true if dropdown should support multiple selections]
349 | * @return {Object/p5.Element} pointer to p5.Element holding created node
350 | */
351 | p5.prototype.createSelect = function(mult) {
352 | var elt = document.createElement('select');
353 | if (mult){
354 | elt.setAttribute('multiple', 'true');
355 | }
356 | var self = addElement(elt, this);
357 | self.option = function(name, value){
358 | var opt = document.createElement('option');
359 | opt.innerHTML = name;
360 | if (arguments.length > 1)
361 | opt.value = value;
362 | else
363 | opt.value = name;
364 | elt.appendChild(opt);
365 | };
366 | self.selected = function(value){
367 | var arr = [];
368 | if (arguments.length > 0){
369 | for (var i = 0; i < this.elt.length; i++){
370 | if (value.toString() === this.elt[i].value){
371 | this.elt.selectedIndex = i;
372 | }
373 | }
374 | return this;
375 | }else{
376 | if (mult){
377 | for (var i = 0; i < this.elt.selectedOptions.length; i++){
378 | arr.push(this.elt.selectedOptions[i].value);
379 | }
380 | return arr;
381 | }else{
382 | return this.elt.value;
383 | }
384 | }
385 | };
386 | return self;
387 | };
388 |
389 | /**
390 | * Creates an <input></input> element in the DOM for text input.
391 | * Use .size() to set the display length of the box.
392 | * Appends to the container node if one is specified, otherwise
393 | * appends to body.
394 | *
395 | * @method createInput
396 | * @param {Number} [value] default value of the input box
397 | * @return {Object/p5.Element} pointer to p5.Element holding created node
398 | */
399 | p5.prototype.createInput = function(value) {
400 | var elt = document.createElement('input');
401 | elt.type = 'text';
402 | if (value) elt.value = value;
403 | return addElement(elt, this);
404 | };
405 |
406 | /**
407 | * Creates an <input></input> element in the DOM of type 'file'.
408 | * This allows users to select local files for use in a sketch.
409 | *
410 | * @method createFileInput
411 | * @param {Function} [callback] callback function for when a file loaded
412 | * @param {String} [multiple] optional to allow multiple files selected
413 | * @return {Object/p5.Element} pointer to p5.Element holding created DOM element
414 | */
415 | p5.prototype.createFileInput = function(callback, multiple) {
416 |
417 | // Is the file stuff supported?
418 | if (window.File && window.FileReader && window.FileList && window.Blob) {
419 | // Yup, we're ok and make an input file selector
420 | var elt = document.createElement('input');
421 | elt.type = 'file';
422 |
423 | // If we get a second argument that evaluates to true
424 | // then we are looking for multiple files
425 | if (multiple) {
426 | // Anything gets the job done
427 | elt.multiple = 'multiple';
428 | }
429 |
430 | // Now let's handle when a file was selected
431 | elt.addEventListener('change', handleFileSelect, false);
432 |
433 | // Function to handle when a file is selected
434 | // We're simplifying life and assuming that we always
435 | // want to load every selected file
436 | function handleFileSelect(evt) {
437 | // These are the files
438 | var files = evt.target.files;
439 | // Load each one and trigger a callback
440 | for (var i = 0; i < files.length; i++) {
441 | var f = files[i];
442 | var reader = new FileReader();
443 | reader.onload = makeLoader(f);
444 | function makeLoader(theFile) {
445 | // Making a p5.File object
446 | var p5file = new p5.File(theFile);
447 | return function(e) {
448 | p5file.data = e.target.result;
449 | callback(p5file);
450 | };
451 | };
452 |
453 | // Text of data?
454 | // This should likely be improved
455 | if (f.type === 'text') {
456 | reader.readAsText(f);
457 | } else {
458 | reader.readAsDataURL(f);
459 | }
460 | }
461 | }
462 | return addElement(elt, this);
463 | } else {
464 | console.log('The File APIs are not fully supported in this browser. Cannot create element.');
465 | }
466 | };
467 |
468 |
469 | /** VIDEO STUFF **/
470 |
471 | function createMedia(pInst, type, src, callback) {
472 | var elt = document.createElement(type);
473 | if (typeof src === 'string') {
474 | src = [src];
475 | }
476 | for (var i=0; ithis
507 | * page for further information about supported formats.
508 | *
509 | * @method createVideo
510 | * @param {String|Array} src path to a video file, or array of paths for
511 | * supporting different browsers
512 | * @param {Object} [callback] callback function to be called upon
513 | * 'canplaythrough' event fire, that is, when the
514 | * browser can play the media, and estimates that
515 | * enough data has been loaded to play the media
516 | * up to its end without having to stop for
517 | * further buffering of content
518 | * @return {Object/p5.Element} pointer to video p5.Element
519 | */
520 | p5.prototype.createVideo = function(src, callback) {
521 | return createMedia(this, 'video', src, callback);
522 | };
523 |
524 | /** AUDIO STUFF **/
525 |
526 | /**
527 | * Creates a hidden HTML5 <audio> element in the DOM for simple audio
528 | * playback. Appends to the container node if one is specified,
529 | * otherwise appends to body. The first parameter
530 | * can be either a single string path to a audio file, or an array of string
531 | * paths to different formats of the same audio. This is useful for ensuring
532 | * that your audio can play across different browsers, as each supports
533 | * different formats. See this
534 | * page for further information about supported formats.
535 | *
536 | * @method createAudio
537 | * @param {String|Array} src path to an audio file, or array of paths for
538 | * supporting different browsers
539 | * @param {Object} [callback] callback function to be called upon
540 | * 'canplaythrough' event fire, that is, when the
541 | * browser can play the media, and estimates that
542 | * enough data has been loaded to play the media
543 | * up to its end without having to stop for
544 | * further buffering of content
545 | * @return {Object/p5.Element} pointer to audio p5.Element
546 | */
547 | p5.prototype.createAudio = function(src, callback) {
548 | return createMedia(this, 'audio', src, callback);
549 | };
550 |
551 |
552 | /** CAMERA STUFF **/
553 |
554 | p5.prototype.VIDEO = 'video';
555 | p5.prototype.AUDIO = 'audio';
556 |
557 | navigator.getUserMedia = navigator.getUserMedia ||
558 | navigator.webkitGetUserMedia ||
559 | navigator.mozGetUserMedia ||
560 | navigator.msGetUserMedia;
561 |
562 | /**
563 | * Creates a new <video> element that contains the audio/video feed
564 | * from a webcam. This can be drawn onto the canvas using video(). More
565 | * specific properties of the stream can be passing in a Constraints object.
566 | * See the
567 | * W3C
568 | * spec for possible properties. Note that not all of these are supported
569 | * by all browsers.
570 | *
571 | * @method createCapture
572 | * @param {String|Constant|Object} type type of capture, either VIDEO or
573 | * AUDIO if none specified, default both,
574 | * or a Constraints boject
575 | * @param {Function} callback function to be called once
576 | * stream has loaded
577 | * @return {Object/p5.Element} capture video p5.Element
578 | * @example
579 | *
612 | */
613 | p5.prototype.createCapture = function() {
614 | var useVideo = true;
615 | var useAudio = true;
616 | var constraints;
617 | var cb;
618 | for (var i=0; i
728 | * var div0 = createDiv('this is the parent');
729 | * var div1 = createDiv('this is the child');
730 | * div0.child(div1); // use p5.Element
731 | *
732 | *
733 | * var div0 = createDiv('this is the parent');
734 | * var div1 = createDiv('this is the child');
735 | * div1.id('apples');
736 | * div0.child('apples'); // use id
737 | *
738 | *
739 | * var div0 = createDiv('this is the parent');
740 | * var elt = document.getElementById('myChildDiv');
741 | * div0.child(elt); // use element from page
742 | *
743 | */
744 | p5.Element.prototype.child = function(c) {
745 | if (typeof c === 'string') {
746 | c = document.getElementById(c);
747 | } else if (c instanceof p5.Element) {
748 | c = c.elt;
749 | }
750 | this.elt.appendChild(c);
751 | return this;
752 | };
753 |
754 |
755 | /**
756 | *
757 | * If an argument is given, sets the inner HTML of the element,
758 | * replacing any existing html. If no arguments are given, returns
759 | * the inner HTML of the element.
760 | *
761 | * @for p5.Element
762 | * @method html
763 | * @param {String} [html] the HTML to be placed inside the element
764 | * @return {Object/p5.Element|String}
765 | */
766 | p5.Element.prototype.html = function(html) {
767 | if (typeof html !== 'undefined') {
768 | this.elt.innerHTML = html;
769 | return this;
770 | } else {
771 | return this.elt.innerHTML;
772 | }
773 | };
774 |
775 | /**
776 | *
777 | * Sets the position of the element relative to (0, 0) of the
778 | * window. Essentially, sets position:absolute and left and top
779 | * properties of style. If no arguments given returns the x and y position
780 | * of the element in an object.
781 | *
782 | * @method position
783 | * @param {Number} [x] x-position relative to upper left of window
784 | * @param {Number} [y] y-position relative to upper left of window
785 | * @return {Object/p5.Element}
786 | * @example
787 | *
788 | * function setup() {
789 | * var cnv = createCanvas(100, 100);
790 | * // positions canvas 50px to the right and 100px
791 | * // below upper left corner of the window
792 | * cnv.position(50, 100);
793 | * }
794 | *
795 | */
796 | p5.Element.prototype.position = function() {
797 | if (arguments.length === 0){
798 | return { 'x' : this.elt.offsetLeft , 'y' : this.elt.offsetTop };
799 | }else{
800 | this.elt.style.position = 'absolute';
801 | this.elt.style.left = arguments[0]+'px';
802 | this.elt.style.top = arguments[1]+'px';
803 | this.x = arguments[0];
804 | this.y = arguments[1];
805 | return this;
806 | }
807 | };
808 |
809 | /**
810 | * Translates an element with css transforms in either 2d (if 2 arguments given)
811 | * or 3d (if 3 arguments given) space.
812 | * @method translate
813 | * @param {Number} x x-position in px
814 | * @param {Number} y y-position in px
815 | * @param {Number} [z] z-position in px
816 | * @param {Number} [perspective] sets the perspective of the parent element in px,
817 | * default value set to 1000px
818 | * @return {Object/p5.Element}
819 | * @example
820 | *