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
.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.
- 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
<svg> element allows for the direct embedding of SVG graphics into your document. To grasp the concept,
let's examine the following example:
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
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:
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.
<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:
The above code draws a rectangle with a purple fill color, a black stroke color, and a stroke width of 4 units.
y define the coordinates of the top-left corner of the rectangle, while the
height determine its size. The
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:
cy specify the coordinates of the circle's center, and the attribute
determines its radius. If the
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:
y of the
<text> element define the
absolute location of the top-left corner, while
dy specify the relative position.
<tspan> element can be utilized to format or reposition specific portions of text within
<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.
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
allows you to embed and display raster images within your SVG content. Here's how you can do it:
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.
- 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.
- SVG: Part of the DOM, accessible by screen readers, built-in accessibility features.
- Canvas: Not directly accessible, requires additional efforts for accessibility.
- 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.
What is the
<svg> element in HTML?
<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?
How is the
<svg> element different from other image formats like JPEG or PNG?
<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
An SVG graphic is defined using various SVG elements within the
<svg> element. These elements include shapes (e.g.,
<path>), text elements (e.g.,
<tspan>), and more. Each element is defined using attributes that specify its properties such as position, size, color, and style.
What is the purpose of the
height attributes in the
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?
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:
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:
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:
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:
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:
This SVG displays the text "Hello SVG!" at position (10, 40) with a font size of 20.
What is the purpose of the
<tspan> child element?
<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
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:
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?
<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:
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
<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:
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
skewX() to manipulate an element's position, size, and orientation.
- Translate: Moves an element along the x and y axes.
- Scale: Enlarges or reduces the size of an element.
- Rotate: Rotates an element around a specified point.
- Skew: Skews an element along the x and y axes.
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.
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.
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
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.
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:
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:
This SVG uses a mask to reveal a circular area within a blue rectangle.
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.