SVG Using D3.js

Make a line SVG element and learn how to apply styling to it using D3.js.

Let’s explore the fundamental SVG’s graphical element line in this lesson. A line in SVG is represented by the </line> tag. We will draw an SVG line without the use of D3.js. Then we will draw the same line in SVG with the help of D3.js.

Draw line

Let’s learn how to draw a line. To draw any graphical elements, first, we will set up svg which will act as a canvas for us to paint on. Then we will draw a line using the </line> tag.

Let’s see the code for drawing a line.

Code of the line without D3.js

Explanation

Let’s dive into the explanation of the above code to understand the drawing of a line.

  • In line 5, we have drawn svg canvas. The height and width are initialized. The color and width of the border have been set to red and 8px respectively.

  • Line 6-8: We have drawn a line using the line tag, where x1, y1 and x2, y2 are the starting point and ending point of the line, respectively. The color of the line is set to black while the width value has been set to 2px.

Draw a line using D3.js

After drawing a line without using D3.js, let’s see how we can draw the same line using D3.js in an easier and more understandable way.

Code of line using D3.js

Explanation

The above code is drawing the same line as we did in the previous code, but with the help of D3.js.

  • From line 1 to line 5 in the JavaScript page we have created the svg tag inside the body tag. With the help of the attr method, we are defining the attributes of svg.

  • From line 7 to line 13 in the JavaScript page, we have created a line inside the svg tag and initialized attributes of the line with the help of the attr method.

The following illustration shows how line is positioned with respect to the origin which lies in the top left corner of the SVG canvas.