SVG Using D3.js
Make a line SVG element and learn how to apply styling to it using D3.js.
We'll cover the following
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.
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. Theheight
andwidth
are initialized. Thecolor
andwidth
of the border have been set tored
and8px
respectively. -
Line 6-8: We have drawn a line using the
line
tag, wherex1
,y1
andx2
,y2
are the starting point and ending point of the line, respectively. Thecolor
of the line is set toblack
while the width value has been set to2px
.
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.
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 thebody
tag. With the help of theattr
method, we are defining the attributes ofsvg
. -
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 theattr
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.