When you are drawing a path with the pen tool, you are placing points on the canvas. Each point has additional two points that help determine the curvature towards the next point, these are called tangents.
The createPath() function allows us to create a path by giving it specific locations in which it will place points, in tangents and out tangents.
It also lets us decide whether the path is closed or open by passing a forth argument, true or false.
It's important to know that createPath() expects, at the very minimum, an array of points.
Tangents and isClosed are optional. if you decide however that you do want to use tangents, know that createPath() expects all three arrays (points, inTangents, outTangents) to be of exactly the same size, otherwise it gets crazy and can throw an error at you.
This expression can get hefty. Scroll to the bottom for a disclaimer. Otherwise, check out these examples:
Creating a Square
Opening the square
Creating a circle without tangents
createPath() gives us an inconceivable amount of power.
One thing we can do is use Math.sin() and Math.cos() to create a circle.
You can read more about the relationship between those functions and a circle here, but in the meantime let's just apply this expression to our path:
How did we do that?
We are using a for loop to run a block of code multiple times. Each time we are calculating the position of the new point using Math.sin() and Math.cos(), and push it to an array of points.
Finally, we give this array of points to the createPath() function, which creates the circle.
It's a cool method although somewhat expensive. In order to get a smooth circle, you'd have to crank the number of segments to a pretty high value.
But hey! It works.
createPath() is not beginners friendly and that's because we are working with a lot of data here.
Going by the same "pen-tool logic", every point has two tangents.
createPath() takes the points, the in-tangents and the out-tangents in 3 separate arrays.
The syntax could be quite scary though. An array of arrays? That's a whole lot of square brackets.
Each point is an array by itself [x,y]. An array of points would look something like [ [x1,y1] , [x2,y2] , [x1,y2] ].
If that's not enough, it's important to know that tangents are calculated in a different space than points.
What does that mean? It means that a tangent at [0,0] would not actually be placed at [0,0], but it would be placed exactly on top of the point it belongs to.
That makes each tangent relative to its point.
None of what we are talking about here is beginners friendly, so don't let this get you down. Try following the examples above to get a more practical sense of how to use it instead of trying to figure the barebones of it if you have no intention to start creating complex path expressions as I did with shpr.