Categories
HTML 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

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="blue" stroke-width="4" fill="red" />
</svg>
 
</body>
</html>

Output:

Example2 – rectangle and rounded rectangle.

<!DOCTYPE html>
<html>
<body>

<svg width="400" height="100">
  <rect width="400" height="100" 
  style="fill:rgb(0,0,255);stroke-width:10;stroke:rgb(0,0,0)" />
</svg>
</br>
<svg width="400" height="180">
  <rect x="50" y="20" rx="20" ry="20" width="150" height="150"
  style="fill:red;stroke:black;stroke-width:5;opacity:0.5" />

</svg>
 
</body>
</html>

Output:

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:yellow;stroke:black;stroke-width:5;fill-rule:evenodd;" />
</svg>
 
</body>
</html>

Output:

Example4 – SVG Logo

<!DOCTYPE html>
<html>
<body>

<svg height="130" width="500">
  <defs>
    <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%"
      style="stop-color:rgb(255,255,0);stop-opacity:1" />
      <stop offset="100%"
      style="stop-color:rgb(255,0,0);stop-opacity:1" />
    </linearGradient>
  </defs>
  <ellipse cx="100" cy="70" rx="85" ry="55" fill="url(#grad1)" />
  <text fill="purple" font-size="45" font-family="Verdana"
  x="50" y="86">Logo</text>
</svg>

</body>
</html>

Output:

Differences Between SVG and Canvas:

SVG is a language for describing 2D graphics in XML. Canvas draws 2D graphics, on the fly (with a 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!

Leave a Reply