Categories
Web development

HTML SVG

The HTML <svg> tag is a container for SVG graphics. HTML <svg> is used to define graphics for the Web. SVG stands for Scalable Vector Graphics.

HTML SVG

SVG has several methods for drawing paths, boxes, circles, text, and graphic images.

Example1 – draw a circle:

<!DOCTYPE html>
<html>
<body>

<svg width="200" height="200">
  <circle cx="100" cy="100" r="60"
  stroke="#264653" stroke-width="6" fill="#2a9d8f" />
</svg>
 
</body>
</html>

Output:

SVG Circle

Example2 – draw a rectangle:

<!DOCTYPE html>
<html>
<body>

<svg width="300" height="100">
  <rect width="300" height="100" 
  style="fill:#2a9d8f;stroke-width:10;stroke:#264653;" />
</svg>
 
</body>
</html>

Output:

SVG Rectangle

Example3 – draw a star.

<!DOCTYPE html>
<html>
<body>

<svg width="300" height="200">
  <polygon points="100,10 40,198 190,78 10,78 160,198"
  style="fill:#e9c46a;stroke:#e9c46a;stroke-width:5;fill-rule:#e9c46a;" />
</svg>
 
</body>
</html>

Output:

SVG Star

Example4 – SVG Logo

<!DOCTYPE html>
<html>
<body>

<svg height="130" width="500">
  <defs>
    <linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%"
      style="stop-color:rgb(42,157,143);stop-opacity:1" />
      <stop offset="100%"
      style="stop-color:rgb(233,196,106);stop-opacity:1" />
    </linearGradient>
  </defs>
  <ellipse cx="100" cy="70" rx="85" ry="55" fill="url(#gradient)" />
  <text fill="#264653" font-size="40" font-family="tahoma"
  x="60" y="85">Logo</text>
</svg>

</body>
</html>

Output:

SVG Logo

Differences Between SVG and Canvas:

SVG is a language for describing 2D graphics in XML. Canvas draws 2D graphics, on the fly (with JavaScript).

SVG is XML-based, which means that every element is available within the SVG DOM. You can attach JavaScript event handlers for an element.

In SVG, each drawn shape is remembered as an object. If attributes of an SVG object are changed, the browser can automatically re-render the shape.

Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it is forgotten by the browser. If its position should be changed, the entire scene needs to be redrawn, including any objects that might have been covered by the graphic.

Note: Before you start to learn SVG you should have some basic understanding of the following: HTML and XML.

Enjoy coding!

Read also:

FAQ SVG

How to resize an SVG image?