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.
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:
28 October 2014
I believe 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 to deepen my understanding of the topics and I hope these articles help others do the same.
I also happen to be well-versed in AWS. If you are a small company or a startup and need help with cloud technologies, get in touch.