PIC-C, Particle In Cell Consulting, LLC. Plasma physics and rarefied gas simulation codes.

HTML5 for Scientific Computing

First, I need to thank John, one of the readers of this blog, for introducing me to HTML5. John took some of the Java examples previously posted on this site, converted them to Javascript, and integrated them with HTML5. You can see his work on the vxB integrator and the FD solver on his site. First time I visited his site, I was quite amazed. I had no idea something like this was actually even possible!

So what is HTML5? It is basically the new standard for writing webpages. It is an update to the existing HTML4 standard, which has been around since 1999. It is still in the draft stage, however most modern browsers, including Chrome, Firefox, and IE, already support many of its features. HTML5 introduces several new tags specifically designed to better capture the new online publishing environment. It also supports drag and drop and introduces support for embedding video and audio content into webpages.

But of even greater interest to the us in the scientific community is the introduction of a new <canvas> tag. This tag defines a rectangular area on the webpage into which you can draw using Javascript! You can see some examples of what is possible on the developer.mozilla.org page. Detailed description of the API is available at whatwg.org. There is also a plethora of amazing examples on hakim.se. With the canvas element, you can draw complicated shapes, stroke their outlines, and fill them with colors and gradients supporting transparency. You can even do animations. This in turn allows us to treat the Internet browser as the GUI for scientific computing codes, especially when coupled with the platform independence of the Java language. Similarly, we can use the canvas element to plot data fetched from a remote server. Often, simulation codes are executed on a remote cluster. The web-based HTML5 interface can be used to periodically download the updated results from the cluster and visualize convergence trends (or other properties of interest). This client side approach is much more dynamic and responsive than using server side technologies for plotting, since it gives the user the ability to interactively manipulate the data without having to fetch a new set of image files from the server. Finally, as John showed, HMTL5 is simply a great tool for demonstration programs.

So what can you do with HTML5? You can for instance make real-time XY plots. The plotting program shown below runs completely in your browser (if you don’t see the graph, try a more recent browser). The source is available here: canvas.html (right click and select Save As). You should see the plot redraw automatically as you select a different function or the number of control points. You can also toggle the markers on and off.

So how does this code work? Whenever any of the radio buttons or the check box is clicked, a Javascript function called recalc() is called. This function first parses the user input from the form. It then creates a list of [x,y] points. These points are sent to another function called draw, which does the actual drawing. This function is a modified version of John’s function to show the vxB integration results. The first step is to grab a pointer to the canvas, which is identified by the id tag “plot”. Canvas supports several types of context, here we grab the one for 2D plotting. The area is next cleared, and a black border is drawn to visualize the plot area.

1
2
3
4
5
6
var canvas = document.getElementById('plot');
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, 501, 501);
 
ctx.strokeStyle = "#000000";
ctx.strokeRect(0, 0, 501, 501);

The canvas is specified in the HTML file using the following markup:

1
2
3
<canvas id="plot" width="501" height="501">
<p>Your browser doesn't support canvas.</p>
</canvas>

We next draw the x and y axis. This is done using the following code. Note, the labels are plotted at the end to make them appear on top of the plotted figure. We start a new path, add the axis endpoints, and finally stroke the path using the selected style.

1
2
3
4
5
6
7
8
9
// draw axis
ctx.lineWidth = 1;
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(250, 15);
ctx.lineTo(250, 485);
ctx.moveTo(15, 250);
ctx.lineTo(485, 250);
ctx.stroke();

We next add the points. The canvas is flipped about the x axis, otherwise the plot would be upside down (by default, the y values increase from top to bottom). The origin is also shifted to correspond to the axis intersection position. We specify red color for the line and a 3px line width. We then start a new line and add the specified points. The scale variable correlates our function’s range of [-1,1],[-1,1] to the pixel span of the plot area. If the user selected to plot the markers, we loop through the points once more, this time adding a circle at each point location. The circle is filled with dark green color.

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
// draw points			
ctx.save();
ctx.translate(250,250);
ctx.scale(1.0, -1.0);
ctx.strokeStyle = "#FF0000";
ctx.lineWidth = 3;
ctx.beginPath();
 
if(points.length > 0) 
{
	x = points[0][0]*scale;
	y = points[0][1]*scale;
	ctx.moveTo(x, y);
	for(i = 0; i < points.length; i += 1) 
	{
		x = points[i][0]*scale;
		y = points[i][1]*scale;
		ctx.lineTo(x, y);
	}
	ctx.stroke();
 
	if (markers)
	{
		ctx.fillStyle="#009900";
		for(i = 0; i < points.length; i += 1) 
		{
			x = points[i][0]*scale;
			y = points[i][1]*scale;
			ctx.beginPath();
			ctx.arc(x, y, 5, 0, 2*Math.PI, false);
			ctx.fill();
			ctx.stroke();
		}
	}
}
 
ctx.restore();

Finally, we add the axis labels.

1
2
3
4
5
// add text, needs to be last to overlap graph
ctx.font = 'italic 20px sans-serif';
ctx.textBaseline = 'top';
ctx.fillText('y(m)', 240, 0);
ctx.fillText('x(m)', 460, 225);

That’s it! The rest of the code is just a basic Javascript manipulation of forms and filling of an array. Feel free to leave a comment if you have any questions. And do not hesitate to contact us if you are interested in our consulting services.

Read more

You may also be interested in the article on Bezier spline interpolation. That article showcases how to use an alternative technique, Scalable Vector Graphics (SVG) to make an interactive webpage. And you will find another HTML5 interactive demo in the article on the Direct Simulation Monte Carlo Method.

Subscribe to the newsletter and follow us on Twitter. Send us an email if you have any questions.

6 comments to “HTML5 for Scientific Computing”

  1. October 30, 2011 at 5:15 pm

    By the way, this is the first of what will be many future posts that will utilize this new technology. We plan to start using HTML5 to make future articles more interactive, with live demos running in your browser…

  2. October 30, 2011 at 7:10 pm

    Also, this site, run by the folks behind Google Chrome, has great info on HTML5, including improving canvas performance: http://www.html5rocks.com/en/tutorials/canvas/performance/

  3. John
    November 2, 2011 at 5:50 pm

    I tried using the vxB Integrator example to compare Java to JavaScript implementations of the Integrator to see how fast they run. I updated the example to include a Java Applet option to calculate the results in addition to Javascript. If the applet is used to calculate the results it sends the results to the canvas element for display in a webpage. Here is the link to the result.

    http://dl.dropbox.com/u/5095342/PIC/picJsJava.html

    Based on the compute times, you can see that the Java version runs about 10X faster than the javascript version of the integrator. You can also see the results of the Java calculation times in the Java Console display.

    It can take a while for the Java computed results to be sent back to javascript for display purposes in canvas but the calculation times are definitely faster using Java. You can find out more about the Java to Javascript interface in a webpage at this link. But passing arrays of data between java and javascript can be a bit slow.

    http://jdk6.java.net/plugin2/liveconnect/

  4. Rick
    December 22, 2011 at 4:36 am

    Nice integration. Will be following.

  5. December 4, 2012 at 10:33 am

    Have you managed to get HTML5 sliders to work
    on Chrome etc.?

    • December 8, 2012 at 10:57 am

      Haven’t tried the sliders yet. What is the problem with using them in Chrome?

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> In addition, you can use$latex ...$ to include equations.