Some time ago I needed to draw a simple chart. I took the hard path not to use any third party library, although there are some with this already implemented, like D3.js. Also I didn’t want to use Canvas, as it would have brought it’s own problems. Soon I realized that SVG does not support curves that crosses all the control points, making them unsuitable for plotting charts.
Converting Catmull-Rom spline to Bezier curve
There is a spline, called Catmull-Rom, which does cross the control points and provide a nice-looking plot. After some googling, I’ve found this excellent article. It has a converter that parses the SVG path d attribute for a special curve, labelled R and converts it’s control points to Bezier curve and replaces the path. It is exactly what I wanted, but I more like that each stuff do one thing, so I’ve separated his code into more reusable parts.
The converter method
The soul of this is the converter. It gets a couple of points and return the control points for the Bezier curve.
We write articles like this regularly. Join our mailing list and let's keep in touch.
It gives back an array where each item is an array of 3 points. These are the control points we’ll use to construct the path.
Constructing the path
We need to construct the path using the control points we got back from the converter. First, we need to move to the start point, then we just draw the curves.
This function gives back the string for the path, ready to use.
First, we need an index.html:
And a test.js:
This draws a nice looking chart, like this:
Join our mailing list
We write articles like this regularly. Let's keep in touch and:
Get coupons for our books and courses when they are available
Download our short ebook on AWS security basics
Get articles and content on a regular basis
28 October 2014
Given a task that requires writing software, an expert provides better and more reliable solutions. I write articles and books to help you be that expert.
I came to believe that great software craftsmanship starts with understanding the underlying technologies better. You can’t rely on “easy solutions” and “quick fixes” when you want dependable systems. I write about technology to deepen my knowledge and also to help others solve problems.