·

photo credit: Polyhedron models via photopin (license)

Drawing a smooth bezier line through several points

Tags: ,

So as some of you might already know, I’m experimenting a bit with SVG lately. Especially the part of procedural generated SVG I find very interesting.
One aspect of drawing in SVG is generating smooth lines through several points. You can simply draw bezier curves to get smooth lines, but how do you know where to put the anchor points? In this article I’ll show you how I manage to draw a smooth bezier line to several points with basic math.

The setup

The first thing to do of course, is plot some random points on your canvas. Something like this:

lines-1442694467
Placing some random points is fairly simple, I simply used a for -loop to get the job done:

To visualise the line we want to smooth, I also drawn some lines from point to point:

lines-1442694485

Calculate the angle of your curves

To smoothen my lines, I want to know what angle I need to set my bezier curves to. To do this, I need to calculate an imaginary line from point X_{0},Y_{0} to X_{2},Y_{2} and calculate it’s angle. Let’s visualise this imaginary line:

lines-1442694511
To calculate it’s angle we can simply calculate it’s normals:

Now we’ve got the angles we can create the anchor points. There is just one question left: Just how long should these anchor points be? To tackle this problem, I set the distance of the anchor points to a portion of the length of the imaginary line. I found that a rough estimate of 20% looks quite smooth:

So let’s have a look at our anchor points:

lines-1442694620

The result

Now we have all this precious data, the steps towards creating a smooth line that runs through all the points are simple. And to put proof by the word, here is the resulting image if I add it all up:

lines-1442694653
Needless to say: although this example is written in PHP, the Math of course applies to any other given language out there.

Visitors give this article an average rating of 4.4 out of 5.

How would you rate this article?

2 thoughts on “Drawing a smooth bezier line through several points”

  1. johnny says:

    Hi Giel

    I’m trying out this example, but i don’t get it to work correctly. Would it be possible to add the whole script, that I can have a look at it and maybe debug my problem. I tried to do it in JavaScript. https://jsfiddle.net/Lg965kqc/3/

    Thanks

    1. fr says:

      Thanks for this article, which put me on the path. I did it in javascript here: https://codepen.io/francoisromain/pen/XabdZm

Leave a Reply