DEV Community 👩‍💻👨‍💻

Vladimir Klepov
Vladimir Klepov

Posted on

I built grafar to visualize maths on the web

Alt Text

I just open-sourced my library for mathematical (and data) visualization, grafar. If you need to plot functions in a browser, or even draw charts with lots of data, you might find it useful, and here's why:

  • Full 3D support via WebGL
  • Simple API
  • Reactive computations for effortless animations and interactivity

Just to show you how easy it is to get started, we'll plot a parametric helix together. You might play along in a codesandbox.

A parametric surface has 2 parameters, let's call them p and q:

const p = grafar.range(-2, 2, 500).select();
const q = grafar.range(0, 1, 2).select();
Enter fullscreen mode Exit fullscreen mode

We define each of them to be a range: p in [-2, 2], q in [0, 1]. A this point, p and q basically hold numeric arrays, nothing too fancy.

Now, we map these parameters to the normal x,y,z coordinates:

const xp =[p, q], (p, q) => Math.cos(8 * p) * q);
const yp =[p, q], (p, q) => Math.sin(8 * p) * q);
Enter fullscreen mode Exit fullscreen mode

The neat thing here is how grafar knows that both p and q represent a degree of freedom, and calls our function for every combination of p and q. What about z? It's equal to p, so no need to map it.

Now we only have to draw the graph on a page. For this, we create a panel in some DOM node, then pin our (x,y,z) to it:

const container = document.getElementById("app");
const panel = grafar.panel(container);[xp, yp, p], panel);
Enter fullscreen mode Exit fullscreen mode

And here's what we get with these 7 lines of code:

Alt Text

Interested? Learn more in the docs

Top comments (0)

Let's see what you can do with JavaScript and a bit of creativity

JS post

Fun with console.log() 💿