I hope that after finishing the Newton’s Cannon simulation you are now eager to go on and create your own web simulations. Of course, every simulation is different, and will present its own challenges. Here, though, is some general advice on how to proceed.
Spend some time looking over all of the reference materials that accompany this tutorial. In these materials I’ve tried to concisely summarize most of the HTML, CSS, and JavaScript features that I’ve used in creating physics simulations for the web. If you invest some time to learn what’s in these materials, then you’ll know where to quickly look up most of the vocabulary and syntax you need.
To complement the dry austerity of the reference sheets, a variety of sample pages also accompany this tutorial. Please try each of these, and then use your browser’s View Source command to see how they work.
You may also wish to look at some more elaborate examples of HTML5 physics simulations. Here is a list of links to example simulations, by myself and others, whose source code you should mostly be able to read after completing this tutorial.
I also recommend downloading each of the sample pages to your own computer, so you can use them to tinker and explore. Here are just a few ideas:
Enough of my ideas! Now that you’ve explored and practiced for a while, I hope you’re ready to create a web simulation of your own design. Now would be a good time to think over your ideas and choose one that seems reasonably straightforward to code. Think about what you want the simulation to accomplish, and how you can implement the needed features using the tools you’ve learned in this tutorial. Sketch what you want the simulation to look like on the screen, and jot down whatever other thoughts you have about the details.
The rest of this document discusses a few miscellaneous issues that you may need to consider as you develop your own simulations in HTML5 and JavaScript.
While it’s natural for a physicist to focus on the underlying calculations that a simulation performs, your audience will learn more (and will grow to include more users) if you also make your best effort to design a good user interface. Doing so often requires quite a bit of creativity and hard work.
Here are some of the questions you should ask yourself as you design a user interface:
While there is no universal recipe for a good user interface, I still rely heavily on three principles emphasized in the original (1985) edition of Inside Macintosh, the programmer’s manual for the first mass-market computer with a graphical user interface. Those principles are responsiveness, permissiveness, and consistency.
Responsiveness means that user inputs have immediate, rather than delayed, effects. Try to provide some instant visual feedback whenever the user checks a box or drags a slider. Don’t make the user choose multiple settings before the simulation even starts.
Permissiveness means that your simulation should allow the user to take any reasonable action at any time. Try not to disable controls while the simulation runs. You want the user to feel in control of the software—not the other way around.
Consistency means using input mechanisms that are similar to what users already understand from using other software. Use push-buttons, checkboxes, and menus in standard ways, and give them standard appearances. If you must invent an unusual input mechanism, try to make it mimic some real-world action such as pointing or pulling. Don’t force users to read lengthy instructions just to figure out how to control your simulation.
Inevitably, there will be times when you need to violate all of these principles. Just be sure to violate them thoughtfully, not accidentally.
For some types of simulations, computational speed is critical. Examples would include many-body simulations of 100 or more particles, solving partial differential equations, and anything that needs to quickly generate intricate, detailed images.
The good news is that in most modern browsers, JavaScript runs only a little slower than native code. That’s because modern browsers employ just-in-time compilation, rather than interpreting your source code anew during every iteration of a loop. On today’s personal computers, this means you can perform about a billion elementary computations per second. That’s about 40 million computations per animation frame, at an aesthetically pleasing frame rate.
Of course, some users may be running your simulation on mobile devices that are slower than your personal computer by an order of magnitude or more. For this reason it may be a good idea to let the user adjust whatever parameter determines the required computational horsepower—such as the number of particles or the resolution of a grid.
One quirk of JavaScript is that it provides no true multi-dimensional arrays.
You can always create an array of arrays, but I’ve found that this can impair
performance. Instead I recommend using large one-dimensional arrays and indexing into
them manually: index = x + xSize*y
. I’ve also found that
it helps to initialize such an array sequentially, nesting the x
loop
inside the y
loop rather than the other way around.
In general, JavaScript just-in-time compilers tend to be temperamental, because they must be able to adapt to bizarre actions like suddenly changing the type of a variable from an integer to a string (or to something even more complex). To optimize performance your code must behave predictably, rather than taking advantage of all of JavaScript’s permissiveness.
To generate intricate images, you may need to manipulate the pixel data directly
via the createImageData
and putImageData
functions.
The Two-Source
Interference sample page demonstrates this method.
If you want to do something complicated for which JavaScript doesn’t provide a built-in solution, you may be able to build on the work of other programmers by using one of the many freely available JavaScript code libraries. Using a library can save you a lot of work, and you’ll often end up with better results. On the other hand, each library comes with its own learning curve, and using one often means sacrificing some flexibility and performance.
Personally, I try to use libraries only when they’ll help me do something that I’m convinced I otherwise wouldn’t be able to do at all (given my limited time and background). This means that I avoid using libraries when they would merely make a task slightly easier: experience has taught me that more often than not, the time spent figuring out how to use the library outweighs the time saved coding with it. Of course, your needs and priorities may be different from mine. But my general aversion to libraries means that I know very little about most of them, so I’m not well qualified to make recommendations. Here, in any case, is an inevitably incomplete list of libraries that, from what I’ve heard, might be useful (or even essential) for certain types of physics simulations:
To use a JavaScript library, your page imports it just like any other external script,
via a (separate) script
element with a src
attribute and no content:
<script src="myLibrary.js"></script>
You can either host a copy of the library on your own server, or provide (in the
src
attribute) the URL of a copy that is hosted on a so-called content
distribution network (CDN). Follow any of the links above for specific instructions
on obtaining and using that library.
Once your web application is complete, how do you share it with the world?
Ideally, your school or institution provides a server to which you can upload web pages of your own creation via FTP or the equivalent. But not everyone is so fortunate. More and more schools are now using content management systems for all their web-based course materials, and these systems won’t always play nice with your page design and JavaScript code. Or you may be in a situation where you have no institution-provided web hosting at all.
The best solution in these cases is probably to just pay for your own web hosting service. I can't recommend a particular vendor, but there are many choices and it shouldn’t cost more than a few dollars per month. You’re looking for “shared” hosting (the inexpensive kind, for sites that won’t get huge amounts of traffic), and you should be sure that the service includes FTP access so you can directly upload your finished web pages.
There are also free hosting services out there in the Cloud, but they all seem to involve compromises. For a web simulation that uses no images or other external files, a good option is CodePen, a site intended for sharing code among web programmers. This site requires that you license your code for unlimited reuse, with attribution (like the examples in this tutorial). You can also try more generic free hosting services such as Weebly or Google Sites, but these typically give you less control over the appearance of your pages, or force you to treat stand-alone pages as attachments (to be downloaded and saved by users, rather than immediately displayed in browsers).
I’ve set up a Google Group for physicists and physics teachers to discuss web programming in HTML5 and JavaScript. You can view the group discussions at:
https://groups.google.com/forum/#!forum/physicshtml5
To join the group (so you can post your own messages), go to this URL and click “Apply to join group”. (You need to have a Google account.) My hope is that, over time, this forum will remedy many of the deficiencies of the tutorial you have just completed.