HTML5 for Scientific Computing

Posted on October 28th, 2011
Previous Article :: Next Article

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 page. Detailed description of the API is available at There is also a plethora of amazing examples on 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. var canvas = document.getElementById('plot');
  2. var ctx = canvas.getContext('2d');
  3. ctx.clearRect(0, 0, 501, 501);
  5. ctx.strokeStyle = "#000000";
  6. ctx.strokeRect(0, 0, 501, 501);

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

  1. <canvas id="plot" width="501" height="501">
  2. <p>Your browser doesn't support canvas.</p>
  3. </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. // draw axis
  2. ctx.lineWidth = 1;
  3. ctx.strokeStyle = "#000000";
  4. ctx.beginPath();
  5. ctx.moveTo(250, 15);
  6. ctx.lineTo(250, 485);
  7. ctx.moveTo(15, 250);
  8. ctx.lineTo(485, 250);
  9. 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. // draw points			
  3. ctx.translate(250,250);
  4. ctx.scale(1.0, -1.0);
  5. ctx.strokeStyle = "#FF0000";
  6. ctx.lineWidth = 3;
  7. ctx.beginPath();
  9. if(points.length > 0) 
  10. {
  11. 	x = points[0][0]*scale;
  12. 	y = points[0][1]*scale;
  13. 	ctx.moveTo(x, y);
  14. 	for(i = 0; i < points.length; i += 1) 
  15. 	{
  16. 		x = points[i][0]*scale;
  17. 		y = points[i][1]*scale;
  18. 		ctx.lineTo(x, y);
  19. 	}
  20. 	ctx.stroke();
  22. 	if (markers)
  23. 	{
  24. 		ctx.fillStyle="#009900";
  25. 		for(i = 0; i < points.length; i += 1) 
  26. 		{
  27. 			x = points[i][0]*scale;
  28. 			y = points[i][1]*scale;
  29. 			ctx.beginPath();
  30. 			ctx.arc(x, y, 5, 0, 2*Math.PI, false);
  31. 			ctx.fill();
  32. 			ctx.stroke();
  33. 		}
  34. 	}
  35. }
  37. ctx.restore();

Finally, we add the axis labels.

  1. // add text, needs to be last to overlap graph
  2. ctx.font = 'italic 20px sans-serif';
  3. ctx.textBaseline = 'top';
  4. ctx.fillText('y(m)', 240, 0);
  5. 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.

8 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:

  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.

    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.

  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?

  6. abdul
    June 5, 2017 at 8:02 am

    how do i draw multiple functions on same canvas

    • June 15, 2017 at 2:18 pm

      You can’t with this demo but in general you just repeat the draw operation.

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=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile=""> In addition, you can use \( ...\) to include equations.