Example using SVG. Inserting Graphics Including an SVG File Using the Object Tag


D3 is most useful when used to create and manipulate SVG-based visuals. Drawing using div"s and other HTML elements is possible, but is a bit clunky and usually introduces display inconsistencies in different browsers. Using SVG is more reliable, visually consistent and faster.

Vector graphics editors such as Illustrator can be used to create SVG files, but we need to learn how to create them using code.

SVG element

Scalable Vector Graphics vector graphics) is a text-based image format. Each SVG image is defined using HTML-like code markup. SVG code can be included directly in an HTML document. Every web browser supports SVG, the only exception being Internet Explorer version 8 and older. SVG is based on XML, so you may notice that elements that don't have a closing tag should be self-closing. For example:

Before you can draw anything, you need to create an SVG element. Think of the SVG element as a canvas on which all your visuals are drawn (In this way, SVG is conceptually similar to the HTML canvas element). At a minimum, it's good to set the width and height using attributes width And height, respectively. If you don't specify them, the SVG will stretch across the entire area of ​​the block.

Here's an SVG element created using the code above:

Don't see him? Click right click in the empty space above and select "View Element Code". Your web inspector should show something similar to this:

Notice that there is an SVG element that spans 500 pixels horizontally and 50 pixels vertically.

Also note that browsers treat pixels as the default unit of measurement. We specified the sizes as 500 and 50, not 500px and 50px. We can specify px explicitly, or any other unit of measurement, for example: em, pt, in, cm, And mm.

Simple Shapes

There are a number of shapes that you can place inside an SVG element. This set includes: rect, circle, ellipse, line, text And path.

If you are familiar with programming computer graphics, you'll recall that typically a pixel-based coordinate system starts at the top left corner and has point coordinates (0,0). Increase X occur from left to right, increase at-top down.

0,0 100,20 200,40

rect draws a square. The square is given by four values: x, y- indicate the point of the upper left corner; width, height- indicate the width and height of the square. This square takes up the entire space of our SVG:

circle draws a circle. A circle is defined by three quantities: cx, cy indicate a point located in the center of the circumscribed circle, r specifies the radius of the circle. This circle is located in the center of our SVG because the attribute cx("center-x") is 250. Example:

ellipse is specified similar to circle, but it is assumed that the radius is specified along two axes: along X and by at. Instead of X use rx, instead of y - ry.

line draws a line. Use x1 And y1 to set the coordinates of the beginning of the line, and x2 And y2 to set the end coordinates. Attribute stroke must set the color of the line, otherwise it will be invisible.

text draws text. Use x to indicate the left edge, and y to indicate the vertical position of the so-called baseline.

Easy-peasy Easy-peasy

the text will inherit the CSS font styles of the parent element unless you set your own styles for the text. Notice how the formatting of the text above matches the text described in this paragraph. We can override formatting styles like this:

Easy-peasy Easy-peasy

Also note that when any visual element hits the border of an SVG element, it will be clipped. Be careful when using text, so that your text squiggles are not cut off. You can see what will happen to the text if you set the baseline (i.e. at) equal to 50, the same as the height of the SVG:

Easy-peasy Easy-peasy

path draws anything more complex than the shapes described above (for example, the silhouette of countries on geomaps) and will be described separately. Now we will work with simple shapes.

Styling SVG Elements

By default, any SVG element has a black fill and no border. If you want anything beyond this, you'll have to apply styles to your element. Common SVG properties are listed below:

  • fill- filling. Color meaning. Just like in CSS color can be specified in several ways:
    • by name: orange;
    • value in hexadecimal number system: #3388aa, #38a;
    • value in RGB format: rgb(10, 150, 20);
    • value in RGBA format: rgba(10, 150, 20, 0.5).
  • stroke- frame. Color meaning.
  • stroke-width- frame width (usually in pixels).
  • opacity- transparency. A numeric value between 0.0 (fully transparent) and 1.0 (fully visible).

WITH text you can also use the following properties:

  • font-family
  • font-size

There are two ways to apply styles to SVG elements: either directly specifying styles within the element as its attributes, or through CSS rules.

Below are some CSS properties set directly on the element circle:

We could do it differently: do not specify style attributes, but specify the style class (just like a regular HTML element):

and then add fill, stroke And stroke-width parameters in the CSS styles of the required class:

Pumpkin ( fill: yellow; stroke: orange; stroke-width: 5; )

The second approach has several obvious advantages:

  1. You can define a class once and apply it to many elements.
  2. CSS code is easier to understand than attributes inside elements.
  3. For these reasons, the second approach is easier to maintain and also faster to implement.

Using CSS to style SVG, however, can be confusing for some. fill, stroke, stroke-width still not CSS properties (the closest CSS equivalents are background-color And border). To help you remember what style sheet rules are specified for SVG elements, it's a good idea to include svg in CSS selector:

Svg .pumpkin ( /* ... */ )

Overlay and order of drawing them

There are no layers as such in SVG and no concept of depth. SVG doesn't support CSS property z-index, thus the shapes can be ordered within a two-dimensional space.

And yet, if you draw several shapes, they overlap:

The order in which elements are listed in the code determines their depth. The purple square is listed first in the code, so it is drawn first. Then a blue square is drawn above the purple one, then a green square is drawn above the blue and purple ones, etc.

Think of SVG shapes as if they were being drawn on a canvas. The color that is applied last covers the rest of the colors, being “in front”.

This aspect of drawing order becomes important when you have multiple visual elements that shouldn't be blocked by anything. For example, you can have axes or value labels on axes that appear on a scatterplot. The axes and labels should be added to the SVG at the end so that they appear before the rest of the elements and are visible.

Transparency

Transparency can be useful when elements of your visualization overlap but you want them all to be visible, or when you want to highlight some elements but make others less noticeable.

There are two ways to apply transparency: use an RGB color with an alpha channel, or set the property opacity numeric value.

You can use rgba() wherever you need to specify a color, for example in attributes fill And stroke. rgba() expects you to pass it 3 values ​​ranging from 0 to 255 for red, green and blue, plus an alpha channel ranging from 0.0 to 1.0.

Note that with the method rgba(), transparency is applied to fill And stroke attributes regardless. The following circles' fill is 75% transparent, and their border is 25% transparent:

To apply transparency to the entire element, you need to set the attribute opacity. Below are the fully visible circles:

and these are the same circles with different transparency:

You can also use the attribute opacity for an element whose colors are specified in the format rgba(). When you do this, transparency multiplies. Below circles use the same RGBA color values ​​for fill And stroke. The first element does not have an attribute set opacity, and the other two have:

Please note that the third circle opacity equal to 0.2 or 20%. However, its purple part has a transparency of 75%. So the purple part ends up being 0.2*0.75 = 0.15 or 15% transparent.

HTML images added to web pages using a tag . The use of graphics makes web pages more visually appealing. Images help better convey the essence and content of a web document.

Using HTML tags And can be created image maps with active areas.

Inserting images into an HTML document

1. Tag

Element represents an image and its fallback content, which is added using the alt attribute. Since the element is lowercase, it is recommended to place it inside a block element, for example,

Or

.

Tag has a required src attribute, the value of which is the absolute or relative path to the image:

For tag The following attributes are available:

Table 1. Tag attributes
Attribute Description, accepted value
alt The alt attribute adds alternative text to an image. Displayed where the image appears before it is loaded or when graphics are disabled, and is also displayed as a tooltip when hovering the mouse over the image.
Syntax: alt="image description" . !}
crossorigin The crossorigin attribute allows you to load images from resources on another domain using CORS requests. Images loaded into canvas using CORS requests can be reused. Allowed values:
anonymous - Cross-origin request is made using an HTTP header, and no credentials are transmitted. If the server does not provide credentials to the server from which the content is requested, the image will be corrupted and its use will be limited.
use-credentials — Cross-origin request is performed by passing credentials.
Syntax: crossorigin="anonymous" .
height The height attribute specifies the height of the image. Can be specified in px or %.
Syntax: height: 300px.
ismap The ismap attribute indicates that the picture is part of a map image located on the server (a map image is an image with clickable areas). When you click on a map image, the coordinates are sent to the server as a URL query string. The ismap attribute is only allowed if the element is a descendant of the element with a valid href attribute.
Syntax: ismap.
longdesc An extended image description URL that complements the alt attribute.
Syntax: longdesc="http://www.example.com/description.txt" .
src The src attribute specifies the path to the image.
Syntax: src="flower.jpg" .
sizes Sets the image size depending on the display options. Only works when the srcset attribute is specified. The attribute value is one or more strings, separated by commas.
srcset Creates a list of image sources that will be selected based on screen resolution. Can be used together with or instead of the src attribute. The attribute value is one or more strings, separated by commas.
usemap The usemap attribute specifies the image as an image map. The value must begin with the # symbol. The value is associated with the value of the name or id attribute of the tag and creates connections between elements And . The attribute cannot be used if the element is a descendant of the element or
width The width attribute specifies the width of the image. Can be specified in px or %.
Syntax: width: 100% .

1.1. Image address

The image address can be specified in full (absolute URL), for example:
url(http://anysite.ru/images/anyphoto.png)

Or via a relative path from document or root directory website:
url(../images/anyphoto.png) - relative path from the document,
url(/images/anyphoto.png) - relative path from the root directory.

This is interpreted as follows:
../ - means go up one level, to the root directory,
images/ - go to the folder with images,
anyphoto.png - points to an image file.

1.2. Image Dimensions

Without setting the image dimensions, the drawing is displayed on the page in its actual size. You can edit the dimensions of the image using the width and height attributes. If only one of the attributes is specified, the second will be calculated automatically to maintain the proportions of the picture.

1.3. Graphic file formats

JPEG format (Joint Photographic Experts Group). JPEG images are ideal for photographs and can contain millions of different colors. Images compress better than GIFs, but text and large areas of solid color may become splotchy.

GIF format (Graphics Interchange Format). Ideal for compressing images that have areas of solid color, such as logos. GIFs allow you to set one of the colors to be transparent, allowing the background of a web page to show through part of the image. GIFs can also include simple animation. GIF images contain only 256 shades, which makes the images look blotchy and unrealistic in color, like posters.

PNG format (Portable Network Graphics). Includes the best features of GIF and JPEG formats. Contains 256 colors and makes it possible to make one of the colors transparent, while compressing images into a smaller size than a GIF file.

APNG format (Animated Portable Network Graphics). An image format based on the PNG format. Allows you to store animation and also supports transparency.

SVG format (Scalable Vector Graphics). An SVG drawing consists of a set of geometric shapes described in XML format: line, ellipse, polygon, etc. Both static and animated graphics are supported. The set of functions includes various transformations, alpha masks, filter effects, and the ability to use templates. SVG images can be resized without losing quality.

BMP format (Bitmap Picture). It is an uncompressed (original) bitmap image whose template is a rectangular grid of pixels. A bitmap file consists of a header, a palette, and graphic data. The header stores information about the graphic image and file (pixel depth, height, width and number of colors). The palette is indicated only in those Bitmap files that contain palette images (8 or less bits) and consist of no more than 256 elements. Graphic data represents the picture itself. The color depth in this format can be 1, 2, 4, 8, 16, 24, 32, 48 bits per pixel.

ICO format (Windows icon). File icon storage format in Microsoft Windows. Also, Windows icon is used as an icon on websites on the Internet. It is a picture of this format that is displayed next to the site address or bookmark in the browser. One ICO file contains one or more icons, the size and color of each of which can be set separately. The icon size can be any size, but the most common are square icons with sides of 16, 32 and 48 pixels.

2. Tag

Tag serves to present a graphic image in the form of a map with active areas. Hotspots are identified by the change in appearance of the mouse cursor when hovered over. By clicking on active areas, the user can navigate to related documents.

The tag has a name attribute available, which specifies the name of the map. The value of the name attribute for the tag must match the name in the element's usemap attribute :

...

Element contains a number of elements , defining interactive areas in the map image.

3. Tag

Tag describes only one active region as part of a client-side image map. The element does not have a closing tag. If one active area overlaps another, the first link from the list of areas will be implemented.

Table 2. Tag attributes
Attribute Brief description
alt Sets alternative text for the active map area.
coords Determines the position of the area on the screen. Coordinates are specified in length units and separated by commas:
For circle— coordinates of the center and radius of the circle;
For rectangle— coordinates of the upper left and lower right corners;
For polygon— coordinates of the polygon vertices in the required order; it is also recommended to indicate the last coordinates, equal to the first, for the logical completion of the figure.
download Complements the href attribute and tells the browser that the resource should be loaded the moment the user clicks the link, instead of, for example, having to open it first (like a PDF file). By specifying a name for an attribute, we are thus giving a name to the loaded object. It is allowed to use an attribute without specifying its value.
href Specifies the URL for the link. An absolute or relative link address can be specified.
hreflang Specifies the language of the associated web document. Only used in conjunction with the href attribute. Accepted values ​​are an abbreviation consisting of a pair of letters indicating the language code.
media Determines what types of devices the file will be optimized for. The value can be any media query.
rel Expands the href attribute with information about the relationship between the current and related document. Accepted values:
alternate - link to an alternative version of the document (for example, a printed form of the page, a translation, or a mirror).
author — link to the author of the document.
bookmark - Permanent URL used for bookmarks.
help - link to help.
license - link to copyright information for this web document.
next/prev - indicates the relationship between individual URLs. Thanks to this markup, Google can determine that the content of these pages is related in a logical sequence.
nofollow - prevents the search engine from following links on a given page or a specific link.
noreferrer - indicates that when following a link, the browser should not send an HTTP request header (Referrer), which records information about which page the site visitor came from.
prefetch - indicates that the target document should be cached, i.e. The browser in the background downloads the contents of the page to its cache.
search - Indicates that the target document contains a search tool.
tag - specifies the keyword for the current document.
shape Specifies the shape of the active area on the map and its coordinates. Can take the following values:
rect — rectangular active area;
circle — active area in the shape of a circle;
poly — active area in the shape of a polygon;
default — the active area occupies the entire area of ​​the image.
target Specifies where the document will be downloaded when the link is clicked. Accepts the following values:
_self — the page is loaded into the current window;
_blank — the page opens in a new browser window;
_parent — the page is loaded into the parent frame;
_top - the page loads in the full browser window.
type Specifies the MIME type of the link files, i.e. file extension.

4. Example of creating an image map

1) Mark the original image into active areas of the desired shape. The coordinates of the areas can be calculated using a photo processing program, for example, Adobe Photoshop or Paint.


Rice. 1. Example of image markup to create a map

2) Set the name of the card by adding it to the tag using the name attribute. We assign the same value to the usemap attribute of the tag .

Jpg" alt="flowers_foto" width="680" height="383" usemap="#flowers"> !} gerbera hyacinth camomiles tulip
Rice. 2. An example of creating an image map, when you click the mouse cursor on a flower, you go to a page with a description

Vector graphics are widely used in printing. But we can also use it for websites using SVG ( Scalable Vector Graphic - scalable vector graphics). According to The W3.org specification defines SVG as:

A language for describing two-dimensional graphics in XML. SVG allows three types of objects: vector graphics (such as paths made up of straight lines and curves), images, and text.

Despite the fact that SVG has been included in the W3C recommendations since August 2011, this technology is practically not used in web projects, although it has a number of advantages over raster images. In this series of lessons we will introduce how to work with SVG elements on web pages.

Advantages of SVG

Resolution independence

Raster images are resolution dependent. Graphics take on an unpresentable appearance when resizing to a certain scale. With vector graphics, this situation is impossible in principle, since everything is represented by mathematical expressions that are automatically recalculated when the scale is changed, and the quality is maintained in any conditions.

Reducing the number of HTTP requests

SVG can be embedded directly in an HTML document using the svg tag, so the browser doesn't need to make any requests to serve the graphics. This approach has a good effect on the loading characteristics of the website.

Styles and scripts

Embedding with the svg tag also makes it easy to style your graphics using CSS. You can change object properties such as background color, transparency, borders, and so on. In a similar way, you can manipulate graphics using JavaScript.

Easy to edit and animate

SVG objects can be animated using CSS or JavaScript. SVG objects can also be modified using a text editor.

Smaller file size

SVG has a smaller file size compared to raster graphics.

Basic SVG Shapes

According to the specification, we can draw several basic shapes: line, polyline, rectangle, circle, ellipse. All elements must be inserted into the tag ... . Let's look at the basic elements in detail.

Line

To display a line in SVG, use the element . He draws a segment for which two points need to be determined: the beginning and the end.

The start of the segment is determined by the attributes x1 and y1 , and the end point is determined by the coordinates in the attributes x2 and y2 .

There are also two other attributes (stroke and stroke-width) that are used to define the color and width of the line, respectively.

This object is similar to , but using the element You can draw several lines at once.

Element Contains the points attribute, which is used to specify the coordinates of points.

The rectangle is drawn using the element . You need to determine the width and height.

To display a circle we use the element . In the following example, we create a circle with a radius of 100, which is defined in the r attribute:

The first two attributes cx and cy define the coordinates of the center. In the above example, we set the value to 102 for both coordinates. The default value is 0.

To display an ellipse we use the element . It works the same as circle, but we can specifically specify the x and y radii using the rx and ry attributes:

Element Displays polyhedral shapes such as triangle, hexagon, etc. For example:

Using a vector graphics editor

Outputting simple SVG objects to HTML is easy. However, as the complexity of the object increases, this practice can lead to a large amount of work required.

But you can use any vector graphics editor (for example, Adobe Illustrator or Inkscape) to create objects. If you have a tool like this, drawing the necessary objects in them is much easier than encoding graphics in an HTML tag.

You can copy vector graphics commands from a file into an HTML document. Or you can embed the .svg file using one of the following elements: embed , iframe and object .

The result will be the same.

Browser support

SVG has good support in the majority modern browsers, excluding IE version 8 and earlier. But the problem can be solved using the JavaScript library. To make things easier, you can use the ReadySetRaphael.com tool to convert SVG code to Raphael format.

First, we download and include the library in the HTML document. Then we load the .svg file, copy and paste the resulting code into the function after loading:

In the body tag we place the following div element with the identifier rsr .

And everything is ready.

In the next tutorial in the series, we'll look at how to style SVG objects in CSS.

This post is the first in a series of articles about SVG (Scalable Vector Graphic), covering the basics of vector graphics on the site.

Vector graphics are widely used in printing. For websites there is SVG, which according to the official specification on w3.org is a language for describing two-dimensional graphics in XML. SVG includes three types of objects: shapes, images, and text. SVG has been around since 1999, and since August 16, 2011 it has been included in the W3C recommendations. SVG is greatly underestimated by web developers, although it has several important advantages.

Advantages of SVG

  • Scaling: Unlike raster graphics, SVG does not lose quality when scaling, so it is convenient to use for retina development.
  • Reducing HTTP requests: when using SVG, the number of calls to the server is reduced, and the site loading speed increases accordingly.
  • Styling and scripting: Using CSS, you can change the graphics settings on the site, such as background, transparency or borders.
  • Animation and editing: when javascript help SVG can be animated and edited in a text or graphics editor (InkScape or Adobe Illustrator).
  • Small size: SVG objects weigh much less than raster images.

Basic SVG Shapes

According to the official specification, you can draw simple objects using SVG: rectangle, circle, line, ellipse, polyline or polygon using a tag svg.

Simple line using tag line with only two parameters - start points (x1 and x2) and end points (y1 and y2):

You can also add stroke and stroke-width attributes or styles to set the color and width:

Style="stroke-width:1; stroke:rgb(0,0,0);"

broken line

The syntax is similar to the previous one, the tag is used polyline, attribute points sets points:

Rectangle

Called by the rect tag, you can add some attributes:

Circle

Called by tag circle, in the example using the attribute r set the radius, cx And cy specify the coordinates of the center:

Ellipse

Called by tag ellipse, works similarly circle, but you can specify two radii - rx And ry:

Polygon

Called by tag polygon, a polygon can have a different number of sides:

Using editors

As you can see from the examples, drawing basic SVG shapes is very simple, but objects can be much more complex. For these, you need to use vector graphics editors, such as Adobe Illustrator or Inkscape, where you can save files in SVG format and then edit them in text editor. You can insert SVG into a page using embed, iframe and object:

An example is an image of an iPod from OpenClipArt.org.

Basic Concepts and Usage

The Scalable Vector Graphics (SVG) format is part of a family of vector graphics standards. Vector graphics differ from raster graphics, in which the color definition of each pixel is stored in some data array. The most common raster formats used on the Internet today are JPEG, GIF, and PNG, each of which has its own advantages and disadvantages.

Commonly used abbreviations
  • CSS: Cascading Style Sheets
  • GIF: Graphics Interchange Format
  • GUI: Graphical User Interface
  • HTML: Hypertext Markup Language
  • JPEG: Joint Photographic Experts Group
  • PNG: Portable Network Graphics
  • SVG: Scalable Vector Graphics
  • XML: Extensible Markup Language

The SVG format has several advantages over any raster format:

  • SVG graphics are created using mathematical formulas that require much less data to be stored in the original file because there is no need to store data for each individual pixel.
  • Vector images scale better. Attempting to scale images published online beyond their original size may result in distorted (or pixelated) images.

    This is because the original pixel data was designed for a specific image size. When resizing, the image renderer makes a guess as to what data should be used to fill the new pixels. Vector images are more resistant to scaling; When changing the image size, the corresponding mathematical formulas can be adjusted.

  • Size source file vector graphics typically have less, so SVG graphics load faster than their raster counterparts and require less bandwidth usage.
  • SVG images are rendered by the browser and can be output software. They can change dynamically, making them particularly suitable for data-driven applications such as charts.
  • The original SVG image file is in text form, making it accessible and search engine friendly.

In this article, you'll learn about the benefits of SVG formats and how they can help you build HTML5 websites.

SVG Basics

Creating SVG graphics uses a completely different process than creating JPEG, GIF, or PNG files. JPEG files, GIF and PNG are usually created using some kind of image editing program, e.g. Adobe Photoshop. SVG images are typically created using some kind of XML-based language. There are graphic user interfaces SVG graphic editors that generate the XML code behind the image for you. However, this article assumes that you are working directly with XML. Information about SVG image editing programs can be found in the section.

Listing 1 shows an example simple XML file An SVG that draws a red circle with a 2px black border.

Listing 1. SVG XML file

The above code produces the image shown in Figure 1.

Figure 1. Red circle with 2 pixel black border

Creating Basic Geometric Shapes

When working with SVG graphics, XML tags are used to create geometric shapes; these XML elements are shown in Table 1.

Table 1. XML elements for creating SVG graphics

line element

The line element is the simplest graphic element. Listing 2 shows how to create a horizontal line.

Listing 2. Creating a horizontal line

The code shown in Listing 2 produces the image shown in Figure 2.

Figure 2. Simple horizontal line

The SVG root tag has width and height attributes that define the drawable area. These attributes act in the same way as the height and width attributes of other HTML elements. In this case, it is established that the work area occupies all available space.

Additionally, this example uses the style tag. SVG graphics support applying styles to content using a wide variety of methods. Styles in this article are included to make images easy to see or when certain attributes, such as color and line width, are required to render a drawing. Additional information about applying styles in SVG graphics can be found in the section.

You can create a line definition by specifying the start and end coordinates in the X and Y axes relative to the workspace. The x1 and y1 attributes represent the start coordinates, and the x2 and y2 attributes represent the end coordinates of the line. To change the direction of drawing a line, you simply need to change the coordinates. For example, by modifying the previous example, you can create a diagonal line as shown in Listing 3.

Listing 3. Creating a diagonal line

Figure 3 shows the output of the code shown in Listing 3.

Figure 3. Diagonal line

polyline element

A broken line is a drawing made up of several lines. Listing 4 shows an example of creating a drawing that looks like the steps of a staircase.

The code shown in Listing 4 produces the image shown in Figure 4.

A polyline is created using the points attribute and by defining pairs of X and Y coordinates separated by commas. In the example shown, the first point is defined as 0.40, where 0 is the X coordinate and 40 is the Y coordinate. However, one set of points is not enough to display the image on the screen, since this set only tells the SVG renderer the starting position. You need at least two sets of points: a starting point and an ending point (for example, points="0.40 40.40").

As with drawing simple lines, the lines do not have to be strictly horizontal or vertical. If you change the values ​​from the previous example, you can get irregular shapes made of lines, like in Listing 5.

Listing 5. Creating a jagged line

The code in Listing 5 produces the image shown in Figure 5.

Figure 5. Jagged line

rect element

To create a rectangle, you just need to define its width and height, as shown in Listing 6.

Listing 6. Creating a rectangle

The code in Listing 6 produces the image shown in Figure 6.

Figure 6. Rectangle

The rect tag can also be used to create a square; a square is simply a rectangle with the same height and width.

circle element

The circle is created by defining the X and Y coordinates of the circle's center and radius, as shown in Listing 7.

Listing 7. Creating a circle

The code in Listing 7 produces the image shown in Figure 7.

Figure 7. Circle

The cx and cy attributes determine the position of the circle's center relative to the canvas. Since the radius is half the width of the circle, when determining it, keep in mind that the total width of the image will be twice the value you specify.

Ellipse element

Essentially, an ellipse is a circle with two radii specified in the code, as shown in Listing 8.

Listing 8. Creating an ellipse

The code in Listing 8 produces the image shown in Figure 8.

Figure 8. Ellipse

In this case, the attributes cx and cy also define the coordinates of the center relative to the canvas. However, with an ellipse, you define one radius for the X-axis and a second radius for the Y-axis using the rx and ry attributes.

polygon element

A polygon is a geometric figure that contains at least three sides. Listing 9 creates a simple triangle.

Listing 9. Creating a triangle

The code in Listing 9 produces the image shown in Figure 9.

Figure 9. Triangle

Similar to working with the polyline element, polygons are created by defining pairs of X and Y coordinates using the points attribute.

By adding pairs of coordinates along the X and Y axes, you can create polygons with any number of sides. For example, by modifying the code in the previous example, you can create a four-sided polygon, as shown in Listing 10.

Listing 10. Creating a four-sided polygon

The code shown in Listing 10 produces the image shown in Figure 10.

Figure 10. Four-sided polygon

You can also use the polygon tag to create geometric shapes complex shape. Listing 11 creates a star drawing.

Listing 11. Creating a star

The code in Listing 11 produces the image shown in Figure 11.

Figure 11. Star polygon

path element

The path element is the most complex of all drawing elements, allowing you to create arbitrary drawings using a set special teams. The path element supports the commands listed in Table 2.

Table 2. Commands supported by the path element

These commands can be used in either upper or lower case. If the command is given in uppercase, the absolute positioning. If a lowercase command is used, relative positioning is applied. Providing examples of the use of all commands is beyond the scope of this article. However, below are a few examples that demonstrate the basics of using these commands.

Using the path element, you can create any simple geometric shapes from the previous examples in this article. Listing 12 uses the path element to create a regular triangle.

Listing 12. Creating a triangle using the path element

The code in Listing 12 produces the image shown in Figure 12.

Figure 12. Triangle created using the path element

The list of commands is defined using the d attribute. IN in this example Drawing begins at the point with coordinates X 150 and Y 0, defined by the move to point command (M150 0). Then use the command to draw a line to the point (L75 200). a line is drawn to a point with coordinates X = 75 and Y = 200. After this, another line is drawn using another command to draw a line to a point (L225 200). Finally, the pattern is closed using the snap (Z) command. No coordinates accompany the Z command, since to close a path, by definition, you draw a line from the current position back to the starting point of the drawing (in this case, the point with coordinates X = 150, Y = 0).

The purpose of the example given was to show you the concept; If you just need to create a regular triangle, it's better to use the polygon tag.

The true "power" of the path element is its ability to create custom shapes, as shown in Listing 13. This example is taken from the Consortium document World Wide Web (W3C) Scalable Vector Graphics (SVG) 1.1 (2nd edition)(see section).

Listing 13. Creating a custom shape using the path element

The code shown in Listing 13 produces the image shown in Figure 13.

Figure 13. Custom shape created using the path element

The path element can be used to create complex designs such as diagrams and squiggly lines. Note that the example provided uses multiple path elements. When creating drawings, you are not limited to any one drawing element in the SVG root tag.

Filters and Gradients

In addition to basic CSS styles, which were used in many of the examples above, SVG graphics also support the use of filters and gradients. In this section, you'll learn how to apply filters and gradients to SVG images.

Filters

Filters can be used to apply special effects to SVG images. SVG supports the following filters.

  • feBlend
  • feColorMatrix
  • feComponentTransfer
  • feComposite
  • feConvolveMatrix
  • feDiffuseLighting
  • feDisplacementMap
  • feFlood
  • feGaussianBlur
  • feImage
  • feMerge
  • feMorphology
  • feOffset
  • feSpecularLighting
  • feTile
  • feTurbulence
  • feDistantLight
  • fePointLight
  • feSpotLight

Listing 14 creates a drop shadow effect that is applied to a rectangle.

Listing 14. Creating a drop shadow effect for a rectangle

The code shown in Listing 14 produces the image shown in Figure 14.

Figure 14. Drop shadow effect for a rectangle

Filters are defined inside the def element (short for “definition”). The filter in this example is assigned an identifier (id) "f1". The filter tag itself has attributes to define the X and Y coordinates, as well as the width and height of the filter. Inside the filter tag, you use the required filter elements and set their properties to the desired values.

Once a filter is defined, you associate it with a specific drawing by using the filter attribute, as shown in . Set the url value to the id attribute value assigned to the filter.

Gradients

Gradient represents a gradual transition from one color to another. There are two main types of gradients: linear and radial. The type of gradient applied is determined by the element you use. The following examples show how to apply linear and radial gradients to an ellipse.

Listing 15 creates an ellipse with a linear gradient.

Listing 15. Creating an ellipse with a linear gradient

The code shown in Listing 15 produces the image shown in Figure 15.

Figure 15. Ellipse with linear gradient

Listing 16 creates an ellipse with a radial gradient.

Listing 16. Creating an ellipse with a radial gradient

The code shown in Listing 16 produces the image shown in Figure 16.

Figure 16. Ellipse with radial gradient

Gradients, like filters, are defined within the def element. Each gradient is assigned an identifier (id). Gradient attributes (such as colors) are set inside the gradient tag using stop elements. To apply a gradient to a picture, set the url value of the fill attribute to the identifier (id) of the desired gradient.

Text and SVG

In addition to creating basic geometric shapes, SVG can also be used to generate text, as shown in Listing 17.

Listing 17. Creating text using SVG
I love you SVG

The code shown in Listing 17 produces the image shown in Figure 17.

Figure 17. Text created with SVG

This example creates an I love SVG sentence using the text element. When using the text element, the actual text displayed is between the opening and closing text elements.

You can display text along different axes and even along paths. In Listing 18, the text is displayed in an arc-shaped path.

Listing 18. Creating text along an arc-shaped path
I love SVG I love SVG

The code shown in Listing 18 produces the image shown in Figure 18.

Figure 18. Text placed along an arc-shaped path

This example adds an additional XML namespace, xlink , to the SVG root tag. The path used to arc the text is created inside the def element, so the path itself is not rendered in the drawing. The display text is nested inside a textPath element, which uses the xlink namespace to refer to the id of the desired path.

As with other SVG graphics, you can also apply filters and gradients to text. Listing 19 applies a filter and gradient to the text.

Listing 19. Creating text with filter and gradient
I love SVG I love SVG

The code shown in Listing 19 produces the image shown in Figure 19.

Figure 19. Text with filter and gradient

Adding SVG XML Code to Web Pages

Once the SVG XML is created, it can be included in HTML pages in several ways. The first method is to directly insert the SVG XML code into the HTML document, as shown in Listing 20.

Listing 20. Directly inserting SVG XML into an HTML document
Embedded SVG

This method is probably the simplest, but it doesn't help reuse. Remember that SVG XML can be saved as a file with the .svg extension. When you save an SVG graphic as a .svg file, you can use embed, object, and iframe elements to include it in Web pages. Listing 21 shows the code for embedding an SVG XML file using the embed element.

Listing 21. Including an SVG XML file using the embed element

Listing 22 shows the code for including an SVG XML file using the object element.

Listing 22. Including an SVG XML file using the object element

Listing 23 shows the code for including an SVG XML file using an iframe element.

Listing 23. Including an SVG XML file using an iframe element

With one of these methods, you can include the same SVG graphic on multiple pages and update it by editing the original .svg file.

Conclusion

This article covers the basics of creating graphics using the SVG format. You learned how to use the built-in geometry elements to create basic geometric shapes, such as a line, rectangle, circle, and so on. You also learned how to use the path element to create complex designs by issuing a sequence of commands, such as moving to a point. , drawing a line to a point and drawing an arc to a point. This article also teaches you how to apply filters and gradients to SVG graphics, including graphics with text, and how to include SVG graphics in HTML pages.

Share