svgdotjs / svg.js

The lightweight library for manipulating and animating SVG
https://svgjs.dev
Other
11.11k stars 1.08k forks source link

Way to automatically draw bezier curve between n points ? #937

Closed cyrilchapon closed 5 years ago

cyrilchapon commented 5 years ago

Hey :)

Thanks for this great lib !

Is there a way to draw (automatically) a bezier curve that goes through an array of points ?

Fuzzyma commented 5 years ago

What you are referring to is not a beziere curve. A beziere curve is defined with its start, end and control points. You have to give all those to define a full curve.

What you are looking for are a type of curve which is not in the svg spec yet. E. G. A catmull Rom curve. But since the development of the specs is pretty much stalled it can take years until you can use it in your browser.

What you can do is: calculate a beziere spline which goes through all your points. However to do that a good portion of maths is required. But iam pretty sure that with a bit of searching, stackoverflowing and copypasta you can create a nice function which creates a path for you that goes through specific points.

Actually there is a good chance that someone wrote this already

cyrilchapon commented 5 years ago

Hey Fuzzyma :)

Thanks. Yes I do am aware of this. To rephrase myself, I was wondering if someone already wrote some sort of plugin, roughly just like :

const bezier = svg.autoSmoothSpline(points, smoothing)

Which calculates appropriates control points to make something clever and smooth, and generates a bezier.

I found that article and this one, but the first and last point (actually the one before the last, and the one after the first) are screwed. This is a good starting point though.. But I'm not a math guy, and can't find something better.

Fuzzyma commented 5 years ago

Ah okay :).

Well - We dont have a plugin for that. However, a quick google search showed me this as the third result: https://www.particleincell.com/2012/bezier-splines/

I think its the same as this one: https://gist.github.com/zdying/1e69c409a1725d636e1ad1501e2e5b01?short_path=e5c90c2

It seems to work very great. Give it a try and if you like, publish it as svg.js plugin ;)

saivan commented 5 years ago

You also might want to look into b splines, thats my favourite way to do this sort of thing https://en.wikipedia.org/wiki/B-spline.

cyrilchapon commented 5 years ago

Hey guys. Thanks ☺️ I found what I want here. This lib exposes a great and clean functional implementation. I could use it with svg.js, I posted a working implementation in there

It was pretty hard to find something working and well writing in decent JS, but here it is ☺️