Paths API in D3.js
A path is applied to create a shape such as Triangle, Rectangle, Circle, Ellipse, Polygon, Curve, Straight Line, etc. A Scalable Vector Graphics (SVG) path helps you show the borderline of any shape. The SVG path allowed for Filled, Stroked, and also use a path clipping. In the chapter, we will explain about the Path APIs.
The below-given script helps you to configure the path.
<script src = “https://d3.js.org/d3-path.v1.min.js”></script>
Methods for Path API
Here, some of the most common path API methods are defined below.
You can apply it, if you want to move the values of x and y coordinates.
This method helps you to generate a new path.
It can be applied to create a new line from the starting point to specified x, y values.
This method allows you to close the existing path.
path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x, y)
You can apply this method at time of drawing the Bezier curve from the existing point to a specified point.
path.quadraticCurveTo(cpx, cpy, x, y)
You can apply this method at the time of drawing the quadratic curve from the current point to a specified point.
path.arc(x, y radius, startAngle, endAngle[, anitclockwise])
This method helps you to draw a circular arc to center startAngle, endAngle, and radius (x, y). If the value of the anticlockwise is true, then the arc is created in anticlockwise direction; otherwise, it is created in a clockwise direction.
path.arcTo(x1, y1, x2, y2, radius)
This method can be applied if you want to draw a circular arc from the existing point to a given point (x1, y1). It also helps you to draw the end line between the starting point(x1, y1) to the ending point(x2, y2).
It provides you a string representation for the path that depends on the SVG data specification of the path.
path.rect(x, y, w, h)
It can be applied if you generate a new subpath, including the four points (x, y), (x + w, y), (x, y + h), and (x + w, y). With the help of these points connected by the straight line indicates the closing of the subpath. It is similar to context.rect and also uses SVG’s lineto command.
Here, we have a basic example of creating a simple line with the help of path API.
<meta charset = "UTF-8">
<title>SVG path line Generator</title>
<svg width = "900" height = "600">
<path transform = "translate(200, 0)" />
<script src = "https://d3js.org/d3.v4.min.js"></script>
var data = [[0, 10], [40, 20], [90, 40], [190, 50], [290, 80]];
var lineGenerator = d3.line();
var pathString = lineGenerator(data);
After the successful execution of the above code, you got the following output.