HTML SVG Element: How to Draw Scalable Vector Graphics

You'll discover in this lesson how to create vector drawings on a website page using the HTML5 SVG element.


What is SVG?

Scalable Vector Graphics (SVG) is an image format based on XML that defines web-based two-dimensional vector graphics. Unlike raster image formats such as .jpg, .gif, and .png, vector images can be resized without compromising their quality.

SVG images are created and edited using a series of statements adhering to the XML schema, which means they can be modified with any text editor, including Notepad. SVG offers several advantages over alternative image formats like JPEG, GIF, and PNG.

  • SVG images can be easily searched, indexed, scripted, and compressed.
  • Real-time creation and modification of SVG images is possible using JavaScript.
  • SVG images can be printed with excellent quality at any resolution.
  • The built-in animation elements of SVG allow for animated content.
  • SVG images can include hyperlinks to other documents.

Tip: Vector images consist of a predetermined set of mathematically defined shapes, while bitmap or raster images are composed of a fixed array of dots known as pixels.

By harnessing the power of the HTML SVG element, web developers can create visually stunning and interactive graphics using Scalable Vector Graphics (SVG), incorporating various techniques such as drawing, styling, transformations, animations, and seamlessly integrating SVG shapes, text, and images to enhance web development graphics and deliver captivating web experiences.


Embedding SVG into HTML Pages

The HTML5 <svg> element allows for the direct embedding of SVG graphics into your document. To grasp the concept, let's examine the following example:

<svg width="300" height="200">
        <text x="40" y="40" style="font-size:20px;">
            The Browser support SVG
        </text>
        Sorry, The browser not support SVG.
    </svg>

Note: Please note that popular modern web browsers such as Chrome, Firefox, Safari, Opera, and Internet Explorer 9 and higher support inline SVG rendering.


Drawing Path and Shapes with SVG

The upcoming section will guide you through the process of drawing fundamental vector-based paths and shapes on web pages using the recently introduced HTML5 <svg> element.

Here is a list of frequently used paths and shapes of SVG elements:

  • <rect>: Draw a rectangle with specified width and height.
  • <circle>: Draw a circle with a specified radius and center.
  • <ellipse>: Draw an ellipse with specified radii and center.
  • <line>: Draw a straight line between two points.
  • <polyline>: Draw a series of connected straight line segments.
  • <polygon>: Draw a closed shape with a series of connected straight line segments.
  • <path>: The most versatile element that allows you to create complex shapes and curves using commands like M (move to), L (line to), C (cubic Bezier curve), Q (quadratic Bezier curve), and more.
  • <text>: Add text to the SVG, allowing you to display text content within your graphics.
  • <tspan>: Used within the <text> element to format or style a portion of the text differently.
  • <image>: Used to embed raster images within the SVG.

These are some of the most commonly used drawing paths and shapes in SVG. You can combine them and apply various attributes like colors, strokes, and styles to create intricate and dynamic graphics.

Here's a list of frequently used attributes of HTML SVG elements:

  • width: Specifies the width of the SVG element or a rectangle.
  • height: Specifies the height of the SVG element or a rectangle.
  • viewBox: Defines the position and dimension of the SVG content within the viewport.
  • fill: Sets the fill color of the SVG shape or text.
  • stroke: Sets the color of the SVG shape's outline or the text's outline.
  • stroke-width: Specifies the width of the SVG shape's outline or the text's outline.
  • cx: Specifies the x-coordinate of the center of a circle or ellipse.
  • cy: Specifies the y-coordinate of the center of a circle or ellipse.
  • r: Specifies the radius of a circle or the x-axis and y-axis radii of an ellipse.
  • x: Specifies the x-coordinate of the top-left corner of a rectangle.
  • y: Specifies the y-coordinate of the top-left corner of a rectangle.
  • points: Defines a list of points for polyline and polygon shapes.
  • d: Defines the path data for the <path> element to create complex shapes and curves.
  • transform: Applies transformations like translation, rotation, and scaling to the SVG element.
  • opacity: Sets the transparency level of the SVG element (0 to 1).
  • font-family: Specifies the font family for the text.
  • font-size: Specifies the font size for the text.
  • text-anchor: Defines the alignment of the text relative to its anchor point.

These attributes allow you to control the appearance and behavior of SVG elements, and they are frequently used in creating interactive and visually appealing graphics for web applications and websites.

Transform your web designs with SVG path drawing using the HTML SVG path element, allowing you to create intricate shapes and designs with precision. Explore the possibilities of filling and stroking SVG shapes, incorporating gradient colors to achieve stunning visual effects. Elevate your designs further with SVG path effects, apply animations using HTML SVG shape attributes, and utilize SVG shape transformations to bring your creations to life.


Drawing a Line

You can create a straight line in SVG using the <line> element. The example below demonstrates how to achieve this:

<svg width="350" height="250">
        <line x1="70" y1="70" x2="300" y2="200" style="stroke:green; stroke-width:7;" />
    </svg>

The above code draws a line from the point (70, 70) to the point (300, 200) with a green stroke color and a stroke width of 7 units.

The attributes x1, x2, y1, and y2 of the <line> element specify the coordinates for drawing the line from (x1, y1) to (x2, y2). The stroke property sets the color of the line to green, and the stroke-width property sets the width of the line to 7 units.

Experience the versatility of SVG line drawing using the HTML SVG line element, as you explore techniques such as rotating lines, applying stroke width and color, and utilizing gradient fills to create visually captivating graphics. Achieve precise alignment and positioning of SVG lines, while also ensuring responsiveness across different devices. Dive into the world of SVG line styling, effects, and animations to add dynamic flair to your web designs.


Drawing a Rectangle

To create rectangles and squares, you can use the <rect> element in SVG. The following example illustrates how to create and style a rectangular shape:

<svg width="350" height="250">
        <rect x="70" y="70" width="200" height="100" style="fill:purple; stroke:black; stroke-width:4;" />
    </svg>

The above code draws a rectangle with a purple fill color, a black stroke color, and a stroke width of 4 units.

The attributes x and y define the coordinates of the top-left corner of the rectangle, while the attributes width and height determine its size. The fill property sets the interior color (fill) of the rectangle to purple. The stroke property sets the outline color (stroke) of the rectangle to black, and the stroke-width property sets the width of the outline to 4 units.

Unleash your creativity with SVG rectangle drawing using the HTML SVG rectangle element. Discover the art of rotating rectangles, applying stroke width and color, and enhancing your designs with gradient-filled rectangles. Achieve precise alignment and positioning of SVG rectangles, ensuring seamless adaptation across various screen sizes. Explore SVG rectangle attributes, styling, transformations, effects, and animations to enhance web projects and elevate designs with boundless possibilities.


Drawing a Circle

Circular shapes can be created using the <circle> element in SVG. The following example demonstrates how to create and style a circular shape:

<svg width="300" height="200">
        <circle cx="150" cy="100" r="80" style="fill:skyblue; stroke:green; stroke-width:5;" />
    </svg>

The attributes cx and cy specify the coordinates of the circle's center, and the attribute r determines its radius. If the cx and cy attributes are not provided, the center is set to (0,0).

Unleash your creativity with SVG circle drawing using the HTML SVG circle element. Explore the possibilities of rotating circles, applying stroke width and color to achieve desired effects, and filling circles with gradient colors to create captivating visuals. Explore precise alignment and positioning of SVG circles, ensuring seamless responsiveness across various screen sizes. Add an extra touch of creativity by incorporating text inside circles to create eye-catching designs, creating visually striking compositions.


Drawing Text with SVG

SVG also allows you to incorporate text into web pages. Text in SVG is treated as a graphic object, enabling the application of various transformations. However, it still functions as selectable and copyable text for users. Let's explore an example to understand this:

<svg width="350" height="150">
        <text x="45" y="40" style="fill:purple; font-size:22px;">
            Welcome to  The my Wwbsite!
        </text>
        <text x="30" y="60" dx="20" dy="20" style="fill:green; font-size:20px;">
            This is a very importent section.
        </text>
    </svg>

The attributes x and y of the <text> element define the absolute location of the top-left corner, while dx and dy specify the relative position.

Additionally, the <tspan> element can be utilized to format or reposition specific portions of text within a <text> element. Text within separate tspans, but within the same text element, can be selected as a whole. However, text in separate text elements cannot be selected simultaneously. Let's examine an example to clarify this concept.

<svg width="350" height="250">
           <text x="40" y="30" style="fill:purple; font-size:22px; transform:rotate(30deg);">
                <tspan style="fill:purple; font-size:30px;">
                Welcome to  The my Wwbsite!
            </tspan>
            <tspan dx="-300" dy="30" style="fill:green; font-size:14px;">
                   This is a very importent section.
            </tspan>
        </text>
    </svg>

Elevate your web designs by incorporating SVG text elements, drawing text with SVG, rotating text, applying strokes and colors, creating vertical text, setting fonts and sizes, and exploring SVG text styling. Enhance your visuals further by adding gradients, animations, and custom fonts to achieve captivating effects.

With HTML SVG text attributes, you can fine-tune stroke width, color, alignment, and responsive rendering, unlocking a world of possibilities for visually engaging and dynamic SVG text elements. Transform your web designs with the SVG text element, allowing you to draw and manipulate text with precision using HTML SVG. Unleash your creativity and deliver captivating typography experiences with SVG text.


Drawing an Image

To draw an image in HTML SVG, you can use the <image> element. The <image> element allows you to embed and display raster images within your SVG content. Here's how you can do it:

<svg width="400" height="300">
<image x="50" y="50" width="300" height="200" xlink:href="image-tree.png" />
</svg>

The xlink:href attribute specifies the path to the image file you want to display. The image file can be in JPEG, PNG, GIF, or any other supported format.

Transform your web designs with SVG image drawing using the HTML SVG image element. Explore the possibilities of rotating images, applying strokes and colors, and utilizing gradient fills to create visually captivating graphics. Enhance your designs further by incorporating text inside SVG images, aligning and positioning them precisely, and leveraging responsive techniques for seamless adaptability.

With responsive techniques, ensure your SVG images adapt seamlessly across different devices. With SVG image attributes and styling, you have the flexibility to customize and bring your images to life, achieving desired alignment, position, and visual effects.

Enhance your visuals with stunning image effects in SVG, such as applying filters, adding shadows, and utilizing transformations to bring depth and dimension to your SVG images. Create captivating transitions and animations using HTML SVG, and experiment with gradients, opacity, and transparency to achieve unique and mesmerizing effects. Unleash your creativity and elevate your designs by incorporating masks, blurring, sharpening, and layering techniques, turning your SVG images into captivating works of art.


Differences between SVG and Canvas

SVG (Scalable Vector Graphics) and Canvas are both widely used in web development for drawing graphics and creating interactive visual elements, but they have fundamental differences in how they work and what they are best suited for. Here are the key differences between SVG and Canvas:

Vector vs. Bitmap:

  • SVG: Scalable Vector Graphics based on mathematical equations, scale without losing quality.
  • Canvas: Bitmap graphics created pixel by pixel, fixed resolution, not as scalable as SVG.

Rendering Approach:

  • SVG: Elements are part of the DOM, individual nodes can be styled and animated using CSS and JS.
  • Canvas: Low-level immediate mode graphics API, operates directly on a raster bitmap.

Accessibility:

  • SVG: Part of the DOM, accessible by screen readers, built-in accessibility features.
  • Canvas: Not directly accessible, requires additional efforts for accessibility.

Interactivity:

  • SVG: Supports interactivity out of the box, event handling for user interactions and animations.
  • Canvas: Requires manual implementation of event listeners for interactivity.

Complexity and Performance:

  • SVG: Simple and static graphics are straightforward, may become less performant for complex and dynamic graphics due to DOM overhead.
  • Canvas: Performs well with complex and dynamic graphics, suitable for real-time rendering and interactivity.

FAQ

What is the <svg> element in HTML?

The <svg> element in HTML is used to embed Scalable Vector Graphics (SVG) content directly into a web page. SVG is an XML-based markup language for describing two-dimensional vector graphics. It allows for the creation of detailed and scalable graphics that can be resized without loss of quality.

What is the difference between SVG and HTML canvas?

SVG is a markup language used to describe vector graphics, while the HTML canvas is a JavaScript-based drawing surface. SVG uses XML syntax to define graphics as a collection of shapes and paths, while the canvas allows for pixel-based drawing using JavaScript.

How is the <svg> element different from other image formats like JPEG or PNG?

The <svg> element produces vector graphics, while image formats like JPEG and PNG produce raster graphics. Vector graphics are based on mathematical descriptions of shapes, allowing them to be resized without loss of quality. Raster graphics, on the other hand, are made up of pixels and can become pixelated when resized.

How is an SVG graphic defined within the <svg> element?

An SVG graphic is defined using various SVG elements within the <svg> element. These elements include shapes (e.g., <rect>, <circle>, <path>), text elements (e.g., <text>, <tspan>), and more. Each element is defined using attributes that specify its properties such as position, size, color, and style.

<svg width="300" height="200">
    <!-- SVG graphic elements go here -->
</svg>

What is the purpose of the width and height attributes in the <svg> element?

The width and height attributes in the <svg> element specify the dimensions of the SVG viewport. The SVG content within the <svg> element is drawn within this viewport. These attributes help determine the size of the rendered SVG graphic on the web page.

What is the viewBox attribute in an SVG element used for?

The viewBox attribute in an SVG element defines the coordinate system and aspect ratio of the SVG content. It specifies the minimum and maximum values of the x and y coordinates, as well as the width and height of the content. The viewBox allows for scaling and resizing of the SVG content to fit different dimensions.

How can you apply styles to SVG elements?

Styles can be applied to SVG elements using attributes like fill for interior color, stroke for outline color, stroke-width for outline width, and more. Additionally, you can use inline styles or reference external CSS for more advanced styling.

How can you create a line using the <line> element in SVG?

To create a line using the <line> element, you define the starting and ending coordinates (x1, y1, x2, y2). Here's an example:

<svg width="200" height="200">
  <line x1="50" y1="50" x2="150" y2="150" stroke="red" stroke-width="2" />
</svg>

This SVG draws a red line from (50, 50) to (150, 150) with a stroke width of 2.

How can you draw a rectangle using the <rect> element in SVG?

To draw a rectangle using the <rect> element, you can define the position (x, y), width, height, and optionally, attributes like fill color and stroke. Here's an example:

<svg width="200" height="150">
  <rect x="50" y="50" width="100" height="75" fill="blue" stroke="black" />
</svg>

This SVG draws a blue rectangle with a black border at position (50, 50) and dimensions 100x75.

How can you create a circle using the <circle> element in SVG?

To create a circle using the <circle> element, you define the center coordinates (cx, cy) and the radius. Here's an example:

<svg width="200" height="200">
  <circle cx="100" cy="100" r="50" fill="green" stroke="black" />
</svg>

This SVG draws a green circle with a black border at center (100, 100) and radius 50.

How can you create an ellipse using the <ellipse> element in SVG?

To create an ellipse using the <ellipse> element, you define the center coordinates (cx, cy), and the radii (rx, ry) for the horizontal and vertical axes. Here's an example:

<svg width="200" height="150">
  <ellipse cx="100" cy="75" rx="80" ry="50" fill="yellow" stroke="black" />
</svg>

This SVG draws a yellow ellipse with a black border at center (100, 75), horizontal radius 80, and vertical radius 50.

How can you create text within an SVG graphic?

You can create text within an SVG graphic using the <text> element. Here's an example:

<svg width="200" height="100">
  <text x="10" y="40" font-family="Arial" font-size="20" fill="black">Hello SVG!</text>
</svg>

This SVG displays the text "Hello SVG!" at position (10, 40) with a font size of 20.

What is the purpose of the <text> element's <tspan> child element?

The <tspan> element is used within the <text> element to apply different styles or attributes to parts of the text content. It allows you to have varying font sizes, colors, and other properties within a single <text> element.

<svg width="300" height="200">
    <text x="50" y="50" font-size="20">
        Hello,
        <tspan fill="red">world!</tspan>
    </text>
</svg>

How can you create a polygon using the <polygon> element in SVG?

To create a polygon using the <polygon> element, you define a series of points using the points attribute. Each point is specified as x,y pairs separated by spaces. Here's an example:

<svg width="200" height="150">
  <polygon points="100,20 150,90 50,90" fill="orange" stroke="black" />
</svg>

This SVG draws an orange polygon with three points at (100, 20), (150, 90), and (50, 90).

How can you create a polyline using the <polyline> element in SVG?

A <polyline> element is similar to a <polygon>, but it only draws connected line segments without closing the shape. Points are defined in the same way using the points attribute. Here's an example:

<svg width="200" height="150">
  <polyline points="50,20 150,20 100,100" fill="none" stroke="blue" />
</svg>

This SVG draws a blue polyline with points at (50, 20), (150, 20), and (100, 100).

How can you create gradients in SVG?

Gradients in SVG are created using the <linearGradient> and <radialGradient> elements within the <defs> section. You define color stops and their positions to create smooth color transitions. Here's an example of a linear gradient:

<svg width="200" height="150">
  <defs>
    <linearGradient id="myGradient" x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%" stop-color="red" />
      <stop offset="100%" stop-color="blue" />
    </linearGradient>
  </defs>
  <rect x="10" y="10" width="180" height="130" fill="url(#myGradient)" />
</svg>

This SVG uses a linear gradient that transitions from red to blue horizontally.

How can you apply transformations to SVG elements?

Transformations in SVG can be applied using the transform attribute. You can use various transformation functions like translate(), scale(), rotate(), and skewX() to manipulate an element's position, size, and orientation.

  1. Translate: Moves an element along the x and y axes.
  2. Scale: Enlarges or reduces the size of an element.
  3. Rotate: Rotates an element around a specified point.
  4. Skew: Skews an element along the x and y axes.
<svg width="300" height="300">
    <!-- Translate -->
    <circle cx="30" cy="30" r="20" fill="blue" 
    transform="translate(50, 50)" />
    <!-- Scale -->
    <rect x="100" y="30" width="40" height="40" fill="green"
          transform="scale(1.5, 0.5)" />
    <!-- Rotate -->
    <ellipse cx="150" cy="150" rx="30" ry="20" fill="orange"
             transform="rotate(45, 150, 150)" />
    <!-- Skew -->
    <polygon points="50,150 80,150 65,180" fill="red"
             transform="skewX(30)" />
</svg>

How can you create a dashed stroke for a shape in SVG?

To create a dashed stroke for a shape in SVG, you can use the stroke-dasharray attribute on the shape's element. The stroke-dasharray attribute specifies a pattern of dashes and gaps.

<svg width="200" height="200">
  <circle cx="100" cy="100" r="50" stroke="black" stroke-width="2" stroke-dasharray="5 3" />
</svg>

This SVG code draws a circle with a dashed border. The stroke-dasharray value "5 3" creates a pattern of 5-pixel dashes followed by 3-pixel gaps.

How can you create a semi-transparent shape in SVG?

To create a semi-transparent shape in SVG, you can use the fill-opacity attribute to adjust the opacity of the fill color.

<svg width="200" height="200">
  <rect x="50" y="50" width="100" height="75" fill="blue" fill-opacity="0.5" stroke="black" />
</svg>

This SVG code draws a semi-transparent blue rectangle with a black border.

How can you include external SVG files in HTML?

External SVG files can be included in HTML using the <object> or <img> elements.

<html>
<body>
    <img src="path/to/your/image.svg" alt="External SVG Image">
    <hr />
    <object data="path/to/your/image.svg" type="image/svg+xml"></object>
</body>
</html>

How can you create responsive SVG graphics?

SVG graphics can be made responsive by using relative units like percentages for sizes and positions. Additionally, the viewBox attribute can be set to maintain the aspect ratio when the SVG scales to different dimensions.

<style>
#svg-container {
            width: 50%; /* Adjust as needed */
            margin: 0 auto;
        }
</style>

<div id="svg-container">
        <svg width="100%" height="100%" viewBox="0 0 200 200">
            <circle cx="100" cy="100" r="80" fill="blue" />
        </svg>
    </div>

How can you create patterns in SVG?

Patterns in SVG are created using the <pattern> element within the <defs> section. They allow you to define a repeating graphical element that can be used to fill other shapes. Here's an example:

<svg width="200" height="150">
  <defs>
    <pattern id="myPattern" width="20" height="20" patternUnits="userSpaceOnUse">
      <rect width="10" height="10" fill="red" />
      <rect x="10" y="10" width="10" height="10" fill="blue" />
    </pattern>
  </defs>
  <rect x="10" y="10" width="180" height="130" fill="url(#myPattern)" />
</svg>

This SVG uses a pattern consisting of red and blue squares to fill a larger rectangle.

How can you create masks in SVG?

Masks in SVG are created using the <mask> element within the <defs> section. Masks allow you to define areas of transparency that can be applied to elements, revealing or hiding underlying content. Here's an example:

<svg width="200" height="150">
  <defs>
    <mask id="myMask">
      <rect width="100%" height="100%" fill="white" />
      <circle cx="100" cy="75" r="40" fill="black" />
    </mask>
  </defs>
  <rect x="10" y="10" width="180" height="130" fill="blue" mask="url(#myMask)" />
</svg>

This SVG uses a mask to reveal a circular area within a blue rectangle.


Conclusion

The HTML5 SVG element opens up endless creative opportunities for web developers. By leveraging shapes, paths, styling, and transformations, developers can unleash their creativity to craft visually stunning and interactive graphics directly in the browser. With a comprehensive set of shape elements like rectangles, circles, lines, ellipses, polygons, polylines, and paths, developers have the tools to build captivating visuals. Additionally, the HTML5 SVG element allows for the incorporation of text, images, and animations, further enhancing the visual experience.