Canvas function plotter

Recently, I stumbled upon excanvas, a project that enables the canvas element in Internet Explorer. This inspired me to start experimenting a little bit with the canvas and its API. The first result of that canvas is a function plotter

The plotter is fairly straightforward in its functionality. It displays a (predefined) set of functions and, using the mouse and keyboard, you can pan and zoom within reasonable boundaries. Nonetheless it took more effort than I thought to get the calculations right. Going from pixels to coordinates and back should be trivial but if there are offsets and zoom factors involved it gets tricky enough for me to scratch my head over.

The interaction with the canvas is very simple:

  • Left-click and drag to pan
  • Press and hold shift while dragging down or up to zoom in and out
  • Double-click somewhere to center that point and zoom in
  • Hold shift and double-click somewhere to center that point and zoom out

You can add your own functions by clicking the 'Add plot' button on the right. In the dialog that pops up you can use x (for x) and all the native JavaScript Math properties and methods without the 'Math' prefix. For example, if you want to plot the function y = sin x + cos x² you enter sin(x) + cos(pow(x, 2)). Try using random() for some strange effects.

All in all it works fairly well. There are some bugs with asymptotic functions (like y = 1/x) and with zooming or panning too far but I'm not going to worry about that. I am pleased with the little details, like the grid and x, y and o at the axes. I would never have thought it is actually not possible to draw a string on the canvas. I managed it with a script by Jeka911 but it appears to have been taken offline.

Anyway, it was very educational. I hope you enjoy it.

Have something to say about this post? Share your thoughts!