D3.js – Introduction to SVG


D3.js – Introduction to SVG


”;


SVG stands for Scalable Vector Graphics. SVG is an XML-based vector graphics format. It provides options to draw different shapes such as Lines, Rectangles, Circles, Ellipses, etc. Hence, designing visualizations with SVG gives you more power and flexibility.

Features of SVG

Some of the salient features of SVG are as follows −

  • SVG is a vector based image format and it is text-based.
  • SVG is similar in structure to HTML.
  • SVG can be represented as a Document object model.
  • SVG properties can be specified as attributes.
  • SVG should have absolute positions relative to the origin (0, 0).
  • SVG can be included as is in the HTML document.

A Minimal Example

Let us create a minimal SVG image and include it in the HTML document.

Step 1 − Create a SVG image and set width as 300 pixel and height as 300 pixel.

<svg width = "300" height = "300">

</svg>

Here, the svg tag starts an SVG image and it has width and height as attributes. The default unit of the SVG format is pixel.

Step 2 − Create a line starting at (100, 100) and ending at (200, 100) and set red color for the line.

<line x1 = "100" y1 = "100" x2 = "200" y2 = "200" 
   style = "stroke:rgb(255,0,0);stroke-width:2"/>

Here, the line tag draws a line and its attributes x1, y1 refers to the starting point and x2, y2 refers to the ending point. The style attribute sets color and thickness of the line using the stroke and the stroke-width styles.

  • x1 − This is the x-coordinate of the first point.

  • y1 − This is the y-coordinate of the first point.

  • x2 − This is the x-coordinate of the second point.

  • y2 − This is the y-coordinate of the second point.

  • stroke − Color of the line.

  • stroke-width − Thickness of the line.

Step 3 − Create a HTML document, “svg_line.html” and integrate the above SVG as shown below −

<!DOCTYPE html>
<html>
   <head>
      <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
      <style>
         body { font-family: Arial; }
      </style>
   </head>

   <body>
      <div id = "svgcontainer">
         <svg width = "300" height = "300">
            <line x1 = "100" y1 = "100" 
               x2 = "200" y2 = "200" style = "stroke:rgb(255,0,0);
               stroke-width:2"/>
         </svg>
      </div>
      <p></p>
      <p></p>
   </body>
</html>

The above program will yield the following result.