Sunday, January 2, 2011

Visualizing GIS data using the HTML5 Canvas element

After implementing some geometry/GIS algorithms, I needed an easy method for visualizing the geometric data that is being processed. In the past, I have used standard ESRI software, such as ArcView or ArcInfo for handling GIS data. I also used C++ with OpenGL to render geometric data. This time, I looked for a really quick and simple solution. Since HTML5 is now available for most browsers (at least the two I use - Firefox and Chrome), I thought I would use the new Canvas element for rendering. This sort of solution, can also be useful for client/server systems.

The Canvas element is quite easy to use. For the purpose of rendering a polyline/polygon one needs to start drawing a path, using beginPath(). Then line are added using the moveTo() and lineTo() calls. The path is closed using stroke() for a polyline, and fill() in the case of a polygon. For rendering points, we can use the arc() call, to draw a complete circle, with a given radius. A subtle point to notice, is that the zero point of the axis is in the upper left corner of the canvas (as opposed to the lower bottom corner, when doing regular geometric draws).
We start by preparing two HTML files, one for the prefix of the final file, and one for the suffix of the file. In the middle we will put the actual rendering  code. Here is the prefix file. Notice the ctx variable, that represents the context of the Canvas element. Also, I scaled and translated the geometry, so it would fit nicely.

And here is the suffix file. Notice that the drawShape() javascript is called when loading the page.

Now, for some Haskell code. First, we define the geometric shapes.

Next, we define the drawShape and drawPoints functions, to create the rendering text. The drawPoints function first produces a moveTo() call for the first point, and lineTo() calls for the remaining points.

And finally, a function for generating the output HTML file (with some example shapes).

Here is the output of the above example.

1 comment:

  1. Nice post. Parents are parents, not Gods. Of course they cannot have all the answers. The way you explain things to your kids should do all the work…it all comes under parenthood and your people skills.