Algebraic Graphs in Canvas

Tweet

How can we include a graph in a web page? Perhaps the obvious choice is to draw it offline, saving it as an image file to be included in the web page using the <img> element. Or maybe draw it using Flash to be included using <object>. Another option is SVG, but that has never been widely supported. Images and Flash have been in widespread use for many years, but today HTML5 gives us a better option – the canvas element.

In this article I will show how use of the canvas element makes it is easy to create graphs using a few lines of JavaScript. This article will avoid the need for a data feed of some description by using simple algebraic equations to generate the data points for the graphs, though, of course, the drawing techniques covered could just as easily be used for graphs based on data read directly from a database.

Graph Paper

Firstly, let’s look at what we’ll be building in this article. The image below shows two fairly simple graphs. Both are straight-line plots, both easy to grasp in concept, and neither with complicated curves.

two graphs

Even a cursory visual inspection reveals there is a common component – the axes and their units. So let’s start with some simple HTML and JavaScript to plot these on the canvas.

X and Y Axes

What HTML do we need? For any drawing using HTML5’s canvas element, all we need to code in HTML is the canvas element itself. For example,

<canvas id="axes"></canvas>

Just as an artist starts with a blank canvas then paints on it with brushes and paint, we are going to code a blank canvas and draw on it using JavaScript. It is best to set the dimensions of the canvas in JavaScript using the canvas.width and canvas.height properties, as this will avoid any problems of scaling by the browser.

When drawing anything in the canvas element we need to bear in mind that by default the origin is at the top left. For the graphs used in this article we, however, want the origin to be in the center of the plot. This requires a little bit of offset thinking. The files axes.html and axes.js show the basic area we’ll be using.

A Simple Equation

For our first graph, let’s start with the simple, straight-line equation y = x. File equation1.html has the same HTML as axes.html but with the addition of a separate canvas for plotting the equation. Separating the various components of canvas drawing is not essential, but it does help when building a complex rendering. Nor is it a new or unusual technique as layering is an integral part of building complex renderings in Photoshop, GIMP, and other similar graphics software. The CSS z-index attribute can be used to position the layers in the order required.

A limitation of line drawing is the types of end cap currently available: only butt, round and square are part of the HTML5 specification. But we want an arrow for end cap of the x and y axes. That’s our first piece of bespoke coding to work around current limitations of the canvas.

The files for this example are equation1.html and equation1.js.

Shading a Graph

Equation 2 is a bit more complicated than the first equation, but not so different that we can’t build on what we’ve learned from Equation 1. In this second example, we need a broken line to show the lack of equality in the equation, and we need shading to show that part of the graph to which the equation applies.

It would be so much easier to draw a broken line if HTML5’s setLineDash() was supported by the browsers. It isn’t, so we need bespoke coding to draw a dashed line. This can be achieved very simply by considering a contiguous line to be composed of a series of small line segments joined end to end.

A canvas feature that we do have at our disposal is the ability to fill an area, which we’ll use for shading the graph. In order to ensure that any shading does not obscure other components of the graph we can adjust the opacity using either CSS or the canvas’s globalAlpha attribute. Note that globalAlpha, as its name suggests, applies to the entire canvas – it’s not possible to change the opacity of individual strokes that are drawn on the canvas. Another good reason for layering.

The files for this example are equation2.html and equation2.js.

Trigonometric Teaser

This article has been focused on algebraic graphs, but there’s no reason why the techniques covered here can not be applied to other forms of graphs. Equation 3 is the simple trigonometric equation y = 2 sin π x. Although this is obviously a curved plot, the technique mentioned for drawing a broken line can also be used to produce a pretty good rendering of a curve, as this example shows.

The files for this example are equation3.html and equation3.js.

All code examples for this article are available for download as a single zipped file.

Real-time Data

I mentioned in the introduction that the simple techniques presented in this article can be used for data read from a database. The use of the canvas for displaying any data in any form, whether it be line graphs, pie charts, bar graphs, etc., is still a comparatively unexplored topic given the youth of this HTML enhancement.

Some real-time examples for which the canvas could prove to be ideal include displaying data from weather stations, patient blood count data on a medical tablet, share price variation during trading, etc.

The days of generating graphical GIFs on the fly are surely numbered.

Summary

In this article we have covered a few essential aspects of using HTML5’s canvas element for the purpose of drawing graphs in a browser. We saw that we can transfer concepts such as layering from graphical work already used in other software. And although implementation of the HTML5 specification is still patchy, we can code workarounds to achieve the results we require.

The canvas is still young, but it has huge potential for transforming the way data can be rendered in a browser.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • moretea

    This is very cool, and I don’t mean to sound contrarian, but… with the number of IE users out there who can’t see canvas elements, I don’t see how this can be widely adopted unless one has some control or knowledge of one’s user base.

    • Anonymous

      IE has had canvas support since 9, hasn’t it?

      • bandcoach

        perhaps, but ie 8/7/6 still have 35% market share of all ie users

  • john jenkins

    Great article! To knit pick “Another option is SVG, but that has never been widely supported” – browser support for SVG is pretty much the same as Canvas (http://caniuse.com/svg / http://caniuse.com/canvas)

  • w5m

    You can use excanvas – a JavaScript library that simulates the canvas element for older IE versions using VML:
    https://code.google.com/p/explorercanvas/