## js2plot - plot 2D functions written in JavaScript

Published

A while ago I wanted to plot a simple mathematical function for a project of mine. No problem, there are a lot of good
function plotters out there. Then I stumbled over the polynomial smooth min function by Inigo Quilez. It
was written for GLSL shaders so it uses functions like `clamp()`

and `mix()`

:

```
float smin( float a, float b, float k )
{
float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
return mix( b, a, h ) - k*h*(1.0-h);
}
```

Ok, getting that into one of those plotters seemed like a hassle. Some of those tools can do amazing things, but I’m a
programmer so I wanted to write the functions in some programming language. I found code snippets and small
libraries to draw function plots into a canvas but nothing simple with panning and zooming. I know there’s *insert your
favorite tool here* but my Google bubble wasn’t trained for that and I didn’t find it. Of course there are the
heavy-weights like Octave or CindyJS but those didn’t
appeal to me at all.

I think you can guess the rest. :D How hard can it be to write a simple plotter with panning and zooming? So I wrote a little tool for my own personal needs: js2plot (GitHub project).

It executes a piece of JavaScript and in there you can call `plot()`

to show the graph of the function. You can then
explore the graph with panning and zooming. Or add more functions, or use variables, JavaScripts `Math`

functions, and
so on. All in all nothing special but for me it’s more convenient to write mathematical code that way (see smooth min
example).

In case that you have the same problem I hope the tool is useful to you. The plotting part is written as a small
library without dependencies. With it you can turn a `canvas`

element into a graph with panning and zooming. But you
have to provide a way for users to write the plotting code.

ps.: I only use the tool on desktops and notebooks so I didn’t implement touch panning and zooming. Panning isn’t a problem but handling to a pinch-zoom still seems like a pain. Reimplementing that gesture isn’t my idea of fun so I skipped it for now.