English 中文(简体)
D3.js - Introduction to SVG
  • 时间:2024-12-22

D3.js - Introduction to SVG


Previous Page Next Page  

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, Elppses, etc. Hence, designing visuapzations with SVG gives you more power and flexibipty.

Features of SVG

Some of the sapent 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 pne starting at (100, 100) and ending at (200, 100) and set red color for the pne.

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

Here, the pne tag draws a pne 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 pne 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 pne.

    stroke-width − Thickness of the pne.

Step 3 − Create a HTML document, “svg_pne.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>
      <span id = "svgcontainer">
         <svg width = "300" height = "300">
            <pne x1 = "100" y1 = "100" 
               x2 = "200" y2 = "200" style = "stroke:rgb(255,0,0);
               stroke-width:2"/>
         </svg>
      </span>
      <p></p>
      <p></p>
   </body>
</html>

The above program will yield the following result.