Recent from talks
Contribute something
Nothing was collected or created yet.
| SVG | |
|---|---|
| Filename extensions | .svg, .svgz |
| Internet media type | image/svg+xml[1][2] |
| Uniform Type Identifier (UTI) | public.svg-image |
| Developed by | W3C |
| Initial release | 4 September 2001 |
| Latest release | 1.1 (Second Edition) 16 August 2011 |
| Type of format | Vector graphics |
| Extended from | XML |
| Standard | W3C SVG |
| Open format? | Yes |
| Website | www |
| Scalable Vector Graphics |
|---|
|
|
Scalable Vector Graphics (SVG) is an XML-based vector graphics format for defining two-dimensional graphics, having support for interactivity and animation. The SVG specification is an open standard developed by the World Wide Web Consortium since 1999.
SVG images are defined in a vector graphics format and stored in XML text files. SVG images can thus be scaled in size without loss of quality, and SVG files can be searched, indexed, scripted, and compressed. The XML text files can be created and edited with text editors or vector graphics editors, and are rendered by most web browsers. SVG can include JavaScript, potentially leading to cross-site scripting.
History
[edit]SVG has been in development within the World Wide Web Consortium (W3C) since 1999 after six competing proposals for vector graphics languages had been submitted to the consortium during 1998 (see below).[3]
The early SVG Working Group decided not to develop any of the commercial submissions, but to create a new markup language that was informed by but not really based on any of them.[3]
SVG was developed by the W3C SVG Working Group starting in 1998, after six competing vector graphics submissions were received that year:
- Web Schematics, from CCLRC[4]
- PGML, from Adobe Systems, IBM, Netscape and Sun Microsystems[5]
- VML, by Autodesk, Hewlett-Packard, Macromedia, Microsoft, and Vision[6]
- Hyper Graphics Markup Language (HGML), by Orange UK and PRP[7]
- WebCGM, from Boeing, PTC, InterCAP Graphics Systems, Inso Corporation, CCLRC, and Xerox[8]
- DrawML, from Excosoft AB[3]
The working group was chaired at the time by Chris Lilley of the W3C.
Early adoption was limited due to lack of support in older versions of Internet Explorer. However, as of 2011, all major desktop browsers began to support SVG. Native browser support offers various advantages, such as not requiring plugins, allowing SVG to be mixed with other content, and improving rendering and scripting reliability. Mobile support for SVG exists in various forms, with different devices and browsers supporting SVG Tiny 1.1 or 1.2. SVG can be produced using vector graphics editors and rendered into raster formats. In web-based applications, Inline SVG allows embedding SVG content within HTML documents.
The SVG specification was updated to version 1.1 in 2011. Scalable Vector Graphics 2 became a W3C Candidate Recommendation on 15 September 2016. SVG 2 incorporates several new features in addition to those of SVG 1.1 and SVG Tiny 1.2.[9]
Version 1.x
[edit]- SVG 1.0 became a W3C Recommendation on 4 September 2001.[10]
- SVG 1.1 became a W3C Recommendation on 14 January 2003.[11] The SVG 1.1 specification is modularized in order to allow subsets to be defined as profiles. Apart from this, there is very little difference between SVG 1.1 and SVG 1.0.
- SVG Tiny 1.2 became a W3C Recommendation on 22 December 2008.[13] It was initially drafted as a profile of the planned SVG Full 1.2 (which has since been dropped in favor of SVG 2),[14] but was later refactored as a standalone specification. It is generally poorly supported.
- SVG 1.1 Second Edition, which includes all the errata and clarifications, but no new features to the original SVG 1.1 was released on 16 August 2011.[15]
- SVG Tiny 1.2 Portable/Secure, a more secure subset of the SVG Tiny 1.2 profile introduced as an IETF draft standard on 29 July 2020.[16] Also known as SVG Tiny P/S. SVG Tiny 1.2 Portable/Secure is a requirement of the BIMI draft standard.[17]
Version 2
[edit]SVG 2 removes or deprecates some features of SVG 1.1 and incorporates new features from HTML5 and Web Open Font Format (WOFF):[18]
- For example, SVG 2 removes several font elements such as
glyphandaltGlyph(replaced by the WOFF). - The
xml:spaceattribute is deprecated in favor of CSS. - HTML5 features such as
translateanddata-*attributes have been added. - Text handling features from SVG Tiny 1.2 are annotated as to be included, but not yet formalized in text.[19] Some other 1.2 features are cherry picked in,[18] but SVG 2 is not a superset of SVG tiny 1.2 in general.
SVG 2 reached the Candidate Recommendation stage on 15 September 2016,[20] and revised versions were published on 7 August 2018 and 4 October 2018.[21] The latest draft was released on 14 September 2025.[22]
Features
[edit]
SVG supports interactivity, animation, and rich graphical capabilities, making it suitable for both web and print applications. SVG images can be compressed with the gzip algorithm, resulting in SVGZ files that are typically 20–50% smaller than the original. SVG also supports metadata, enabling better indexing, searching, and retrieval of SVG content.
SVG allows three types of graphic objects: vector graphic shapes (such as paths consisting of straight lines and curves), bitmap images, and text. Graphical objects can be grouped, styled, transformed and composited into previously rendered objects. The feature set includes nested transformations, clipping paths, alpha masks, filter effects and template objects. SVG drawings can be interactive and can include animation, defined in the SVG XML elements or via scripting that accesses the SVG Document Object Model (DOM).
SVG uses CSS for styling and JavaScript for scripting. Text, including internationalization and localization, appearing in plain text within the SVG DOM, enhances the accessibility of SVG graphics.[15]
Printing
[edit]Though the SVG Specification primarily focuses on vector graphics markup language, its design includes the basic capabilities of a page description language like Adobe's PDF. It contains provisions for rich graphics, and is compatible with CSS for styling purposes. SVG has the information needed to place each glyph and image in a chosen location on a printed page.[23]
Scripting and animation
[edit]SVG drawings can be dynamic and interactive. Time-based modifications to the elements can be described in SMIL, or can be programmed in a scripting language (e.g. JavaScript). The W3C explicitly recommends SMIL as the standard for animation in SVG.[24]
A rich set of event handlers such as "onmouseover" and "onclick" can be assigned to any SVG graphical object to apply actions and events.
Mobile profiles
[edit]Because of industry demand, two mobile profiles were introduced with SVG 1.1: SVG Tiny (SVGT) and SVG Basic (SVGB).
These are subsets of the full SVG standard, mainly intended for user agents with limited capabilities. In particular, SVG Tiny was defined for highly restricted mobile devices such as cellphones; it does not support styling or scripting.[25] SVG Basic was defined for higher-level mobile devices, such as smartphones.
In 2003, the 3GPP, an international telecommunications standards group, adopted SVG Tiny as the mandatory vector graphics media format for next-generation phones. SVGT is the required vector graphics format and support of SVGB is optional for Multimedia Messaging Service (MMS) and Packet-switched Streaming Service.[26][27][28] It was later[when?] added as required format for vector graphics in 3GPP IP Multimedia Subsystem (IMS).[29]
Neither mobile profile includes support for the full Document Object Model (DOM), while only SVG Basic has optional support for scripting, but because they are fully compatible subsets of the full standard, most SVG graphics can still be rendered by devices which only support the mobile profiles.[30]
SVGT 1.2 adds a microDOM (μDOM), styling and scripting.[25] SVGT 1.2 also includes some features not found in SVG 1.1, including non-scaling strokes, which are supported by some SVG 1.1 implementations, such as Opera, Firefox, and WebKit. As shared code bases between desktop and mobile browsers increased, the use of SVG 1.1 over SVGT 1.2 also increased.
Compression
[edit]SVG images, being XML, contain many repeated fragments of text, so they are well suited for lossless data compression algorithms. When an SVG image has been compressed with the gzip algorithm, it is referred to as an "SVGZ" image and uses the corresponding .svgz filename extension. Conforming SVG 1.1 viewers will display compressed images.[31] An SVGZ file is typically 20 to 50 percent of the original size.[32] W3C provides SVGZ files to test for conformance.[33]
Design
[edit]The SVG 1.1 specification defines 14 functional areas or feature sets:[11]
- Paths
- Simple or compound shape outlines are drawn with curved or straight lines that can be filled in, outlined, or used as a clipping path. Paths have a compact coding.
- For example,
M(for "move to") precedes initial numeric x and y coordinates, andL(for "line to") precedes a point to which a line should be drawn. Further command letters (C,S,Q,T, andA) precede data that is used to draw various Bézier and elliptical curves.Zis used to close a path. - In all cases, absolute coordinates follow capital letter commands and relative coordinates are used after the equivalent lower-case letters.[34]
- Basic shapes
- Straight-line paths and paths made up of a series of connected straight-line segments (polylines), as well as closed polygons, circles, and ellipses can be drawn. Rectangles and round-cornered rectangles are also standard elements.[35]
- Text
- Unicode character text included in an SVG file is expressed as XML character data. Many visual effects are possible, and the SVG specification automatically handles bidirectional text (for composing a combination of English and Arabic text, for example), vertical text (as Chinese or Japanese may be written) and characters along a curved path (such as the text around the edge of the Great Seal of the United States).[36]
- Painting
- SVG shapes can be filled and outlined (painted with a color, a gradient, or a pattern). Fills may be opaque, or have any degree of transparency.
- "Markers" are line-end features, such as arrowheads, or symbols that can appear at the vertices of a polygon.[37]
- Color
- Colors can be applied to all visible SVG elements, either directly or via
fill,stroke, and other properties. Colors are specified in the same way as in CSS2, i.e. using names likeblackorblue, in hexadecimal such as#2f0or#22ff00, in decimal likergb(255,255,127), or as percentages of the formrgb(100%,100%,50%).[38] - Gradients and patterns
- SVG shapes can be filled or outlined with solid colors as above, or with color gradients or with repeating patterns. Color gradients can be linear or radial (circular), and can involve any number of colors as well as repeats. Opacity gradients can also be specified. Patterns are based on predefined raster or vector graphic objects, which can be repeated in
xandydirections. Gradients and patterns can be animated and scripted.[39] - Since 2008, there has been discussion[40][41] among professional users of SVG that either gradient meshes or preferably diffusion curves could usefully be added to the SVG specification. It is said that a "simple representation [using diffusion curves] is capable of representing even very subtle shading effects"[42] and that "Diffusion curve images are comparable both in quality and coding efficiency with gradient meshes, but are simpler to create (according to several artists who have used both tools), and can be captured from bitmaps fully automatically."[43] The current draft of SVG 2 includes gradient meshes.[44]
- Clipping, masking and compositing
- Graphic elements, including text, paths, basic shapes and combinations of these, can be used as outlines to define both inside and outside regions that can be painted (with colors, gradients and patterns) independently. Fully opaque clipping paths and semi-transparent masks are composited together to calculate the color and opacity of every pixel of the final image, using alpha blending.[45]
- Filter effects[46]
- A filter effect consists of a series of graphics operations that are applied to a given source vector graphic to produce a modified bitmapped result.
- Interactivity
- SVG images can interact with users in many ways. In addition to hyperlinks as mentioned below, any part of an SVG image can be made receptive to user interface events such as changes in focus, mouse clicks, scrolling or zooming the image and other pointer, keyboard and document events. Event handlers may start, stop or alter animations as well as trigger scripts in response to such events.[47]
- Linking
- SVG images can contain hyperlinks to other documents, using XLink. Through the use of the
<view>element or a fragment identifier, URLs can link to SVG files that change the visible area of the document. This allows for creating specific view states that are used to zoom in/out of a specific area or to limit the view to a specific element. This is helpful when creating sprites. XLink support in combination with the<use>element also allow linking to and re-using internal and external elements. This allows coders to do more with less markup and makes for cleaner code.[48] - Scripting
- All aspects of an SVG document can be accessed and manipulated using scripts in a similar way to HTML. The default scripting language is JavaScript and there are defined Document Object Model (DOM) objects for every SVG element and attribute. Scripts are enclosed in
<script>elements. They can run in response to pointer events, keyboard events and document events as required.[49] - Animation
- SVG content can be animated using the built-in animation elements such as
<animate>,<animateMotion>and<animateColor>. Content can be animated by manipulating the DOM using ECMAScript and the scripting language's built-in timers. SVG animation has been designed to be compatible with current and future versions of Synchronized Multimedia Integration Language (SMIL). Animations can be continuous, they can loop and repeat, and they can respond to user events, as mentioned above.[50] - Fonts
- As with HTML and CSS, text in SVG may reference external font files, such as system fonts. If the required font files do not exist on the machine where the SVG file is rendered, the text may not appear as intended. To overcome this limitation, text can be displayed in an SVG font, where the required glyphs are defined in SVG as a font that is then referenced from the
<text>element.[51] - Metadata
- In accord with the W3C's Semantic Web initiative, SVG allows authors to provide metadata about SVG content. The main facility is the
<metadata>element, where the document can be described using Dublin Core metadata properties (e.g. title, creator/author, subject, description, etc.). Other metadata schemas may also be used. In addition, SVG defines<title>and<desc>elements where authors may also provide plain-text descriptive material within an SVG image to help indexing, searching and retrieval by a number of means.[52]
An SVG document can define components including shapes, gradients etc., and use them repeatedly. SVG images can also contain raster graphics, such as PNG and JPEG images, and further SVG images.
This code will produce the colored shapes shown in the image, excluding the grid and labels:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="391" height="391" viewBox="-70.5 -70.5 391 391" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<rect fill="#fff" stroke="#000" x="-70" y="-70" width="390" height="390"/>
<g opacity="0.8">
<rect x="25" y="25" width="200" height="200" fill="lime" stroke-width="4" stroke="pink" />
<circle cx="125" cy="125" r="75" fill="orange" />
<polyline points="50,150 50,200 200,200 200,100" stroke="red" stroke-width="4" fill="none" />
<line x1="50" y1="50" x2="200" y2="200" stroke="blue" stroke-width="4" />
</g>
</svg>
Implementation
[edit]The use of SVG on the web was limited by the lack of support in older versions of Internet Explorer (IE). Many websites that serve SVG images also provide the images in a raster format, either automatically by HTTP content negotiation or by allowing the user directly to choose the file.
Web browsers
[edit]Konqueror was the first browser to support SVG in release version 3.2 in February 2004.[53] As of 2011, all major desktop browsers, and many minor ones, have some level of SVG support. Other browsers' implementations are not yet complete; see comparison of layout engines for further details.
Some earlier versions of Firefox (e.g. versions between 1.5 and 3.6[54]), as well as a few other, now outdated, web browsers capable of displaying SVG graphics, needed them embedded in <object> or <iframe> elements to display them integrated as parts of an HTML webpage instead of using the standard way of integrating images with <img>.[55] However, SVG images may be included in XHTML pages using XML namespaces.[56]
Tim Berners-Lee, the inventor of the World Wide Web, was critical of early versions of Internet Explorer for its failure to support SVG.[57]
- Opera (since 8.0) has support for the SVG 1.1 Tiny specification, while Opera 9 includes SVG 1.1 Basic support and some of SVG 1.1 Full. Opera 9.5 has partial SVG Tiny 1.2 support. It also supports SVGZ (compressed SVG).
- Browsers based on the Gecko layout engine (such as Firefox, Flock, Camino, and SeaMonkey) all have had incomplete support for the SVG 1.1 Full specification since 2005. The Mozilla site has an overview of the modules which are supported in Firefox[58] and of the modules which are in development.[59] Gecko 1.9, included in Firefox 3.0, adds support for more of the SVG specification (including filters).[60]
- Pale Moon, which uses the Goanna layout engine (a fork of the Gecko engine), supports SVG.
- Browsers based on WebKit (such as Apple's Safari, Google Chrome, and The Omni Group's OmniWeb) have had incomplete support for the SVG 1.1 Full specification since 2006.[61]
- Amaya has partial SVG support.
- Internet Explorer 8 and older versions do not support SVG.[62][63] IE9 (released 14 March 2011) supports the basic SVG feature set.[64] IE10 extended SVG support by adding SVG 1.1 filters.[65]
- Microsoft Edge Legacy supports SVG 1.1.[66]
- The Maxthon Cloud Browser also supports SVG.[citation needed]
There are several advantages to native and full support: plugins are not needed, SVG can be freely mixed with other content in a single document, and rendering and scripting become considerably more reliable.[67]
Mobile devices
[edit]Support for SVG may be limited to SVGT on older or more limited smart phones or may be primarily limited by their respective operating system. Adobe Flash Lite has optionally supported SVG Tiny since version 1.1. At the SVG Open 2005 conference, Sun demonstrated a mobile implementation of SVG Tiny 1.1 for the Connected Limited Device Configuration (CLDC) platform.[68]
Mobiles that use Opera Mobile, as well as the iPhone's built in browser, also include SVG support. However, even though it used the WebKit engine, the Android built-in browser did not support SVG prior to v3.0 (Honeycomb).[69] Prior to v3.0, Firefox Mobile 4.0b2 (beta) for Android was the first browser running under Android to support SVG by default.[70]
The level of SVG Tiny support available varies from mobile to mobile, depending on the SVG engine installed. Many newer mobile products support additional features beyond SVG Tiny 1.1, like gradient and opacity; this is sometimes referred to as "SVGT 1.1+", though there is no such standard.
RIM's BlackBerry has built-in support for SVG Tiny 1.1 since version 5.0.[71] Support continues for WebKit-based BlackBerry Torch browser in OS 6 and 7.[72]
Nokia's S60 platform has built-in support for SVG. For example, icons are generally rendered using the platform's SVG engine. Nokia has also led the JSR 226: Scalable 2D Vector Graphics API expert group that defines Java ME API for SVG presentation and manipulation. This API has been implemented in S60 Platform 3rd Edition Feature Pack 1 and onward.[73] Some Series 40 phones also support SVG (such as Nokia 6280).[74]
Most Sony Ericsson phones beginning with K700 (by release date) support SVG Tiny 1.1. Phones beginning with K750 also support such features as opacity and gradients. Phones with Sony Ericsson Java Platform-8 have support for JSR 226.[citation needed]
Windows Phone has supported SVG since version 7.5.
SVG is also supported on various mobile devices from Motorola, Samsung, LG, and Siemens mobile/BenQ-Siemens. eSVG, an SVG rendering library mainly written for embedded devices, is available on some mobile platforms.[75][76]
Authoring
[edit]
SVG images can be hand coded or produced by the use of a vector graphics editor, such as Inkscape, Adobe Illustrator, Adobe Animate, or CorelDRAW, and rendered to common raster image formats such as PNG using the same software. Additionally, editors like Inkscape and Boxy SVG provide tools to trace raster images to Bézier curves typically using image tracing back-ends like potrace,[77] autotrace, and imagetracerjs.
Software can be programmed to render SVG images by using a library such as librsvg used by GNOME since 2000, Batik and ThorVG (Thor Vector Graphics) since 2020 for lightweight systems. SVG images can also be rendered to any desired popular image format by using ImageMagick, a free command-line utility (which also uses librsvg under the hood).
For web-based applications, the mode of usage termed Inline SVG allows SVG content to be embedded within an HTML document using an <svg> tag. Its graphical capabilities can then be employed to create sophisticated user interfaces as the SVG and HTML share context, event handling, and CSS.
Other uses for SVG include embedding for use in word processing (e.g. with LibreOffice) and desktop publishing (e.g. Scribus), plotting graphs (e.g. gnuplot), and importing paths (e.g. for use in GIMP or Blender). The application services Microsoft 365 and Microsoft Office 2019 offer support for exporting,[78] importing and editing SVG images. The Uniform Type Identifier for SVG used by Apple is public.svg-image and conforms to public.image and public.xml.
Security
[edit]As a document format, similar to HTML documents, SVG can host scripts or CSS. This is an issue when an attacker can upload a SVG file to a website, such as a profile picture, and the file is treated as a normal picture but contains malicious content.[79] For instance, if an SVG file is deployed as a CSS background image, or a logo on some website, or in some image gallery, then when the image is loaded in a browser it activates a script or other content. This could lock up the browser (the Billion laughs attack), but could also lead to HTML injection and cross-site scripting attacks. The W3C therefore stipulate certain requirements when SVG is simply used for images: SVG Security.[80]
The W3C says that Inline SVG (an SVG file loaded natively on a website) is considered less of a security risk because the content is part of a greater document, and so scripting and CSS would not be unexpected.[80]
Related work
[edit]The MPEG-4 Part 20 standard – Lightweight Application Scene Representation (LASeR) and Simple Aggregation Format (SAF) is based on SVG Tiny.[81] It was developed by MPEG (ISO/IEC JTC 1/SC29/WG11) and published as ISO/IEC 14496-20:2006.[82] SVG capabilities are enhanced in MPEG-4 Part 20 with key features for mobile services, such as dynamic updates, binary encoding, state-of-art font representation.[83] SVG was also accommodated in MPEG-4 Part 11, in the Extensible MPEG-4 Textual (XMT) format – a textual representation of the MPEG-4 multimedia content using XML.[84]
See also
[edit]References
[edit]- ^ "Media Type Registration for image/svg+xml". W3C. Archived from the original on 19 February 2014. Retrieved 5 February 2014.
- ^ St. Laurent, Simon; Makoto, Murata; Kohn, Dan (January 2001). XML Media Types. Network Working Group. doi:10.17487/RFC3023. RFC 3023. Proposed Standard. sec. 8.19. Obsoleted by RFC 7303. Updated by RFC 6839. Obsoletes RFC 2376. Updates RFC 2048.
- ^ a b c "Secret Origin of SVG". World Wide Web Consortium. 21 December 2007. Archived from the original on 24 December 2020. Retrieved 1 January 2011.
- ^ "Schematic Graphics". W3C. Archived from the original on 31 January 2022. Retrieved 19 July 2019.
- ^ Al-Shamma, Nabeel; Robert Ayers; Richard Cohn; Jon Ferraiolo; Martin Newell; Roger K. de Bry; Kevin McCluskey; Jerry Evans (10 April 1998). "Precision Graphics Markup Language (PGML)". W3C. Archived from the original on 16 December 2021. Retrieved 8 May 2009.
- ^ Mathews, Brian; Brian Dister; John Bowler; Howard Cooper stein; Ajay Jindal; Tuan Nguyen; Peter Wu; Troy Sandal (13 May 1998). "Vector Markup Language (VML)". W3C. Archived from the original on 6 November 2021. Retrieved 8 May 2009.
- ^ "Hyper Graphics Markup Language (HGML)". W3C. Archived from the original on 7 April 2022. Retrieved 19 July 2019.
- ^ "WebCGM Profile". xml.coverpages.org. Archived from the original on 14 August 2022. Retrieved 4 March 2019.
- ^ "Scalable Vector Graphics (SVG) 2". W3C. Archived from the original on 27 January 2017. Retrieved 28 January 2017.
- ^ Ferraiolo, Jon (4 September 2001). "Scalable Vector Graphics (SVG) 1.0 Specification". World Wide Web Consortium. Archived from the original on 11 May 2008. Retrieved 24 February 2010.
- ^ a b Ferraiolo, Jon (16 August 2011). "Scalable Vector Graphics (SVG) 1.1 Specification". World Wide Web Consortium. Archived from the original on 16 September 2012. Retrieved 14 April 2016.
- ^ Capin, Tolga (15 June 2009). "Mobile SVG Profiles: SVG Tiny and SVG Basic". World Wide Web Consortium. Archived from the original on 9 October 2010. Retrieved 24 October 2010.
- ^ Andersson, Ola (22 December 2008). "Scalable Vector Graphics (SVG) Tiny 1.2 Specification". World Wide Web Consortium. Archived from the original on 7 December 2020. Retrieved 24 February 2010.
- ^ Dengler, Patrick (8 July 2010). "Getting to SVG 2.0: A report from the SVG Working Group Face-to-Face (May 24th – June 1st 2010)". Microsoft Developer Network. Microsoft. Archived from the original on 12 May 2016. Retrieved 26 August 2010.
- ^ a b "Scalable Vector Graphics (SVG) 1.1 (Second Edition)". W3C. Archived from the original on 24 September 2011. Retrieved 29 August 2011.
- ^ Brotman, Alex; Adams, J. Trent (29 July 2020). "SVG Tiny Portable/Secure". Ietf Datatracker. Archived from the original on 14 February 2021. Retrieved 9 February 2021.
- ^ "Implementation Guide". BIMI Group. Archived from the original on 28 February 2021. Retrieved 9 February 2021.
- ^ a b "Appendix K: Changes from SVG 1.1". World Wide Web Consortium. 26 May 2020. Archived from the original on 4 February 2021. Retrieved 31 December 2020.
- ^ "Chapter 11: Text". World Wide Web Consortium. 26 May 2020. Archived from the original on 21 April 2021. Retrieved 31 December 2020.
- ^ "Scalable Vector Graphics (SVG) 2". World Wide Web Consortium. 15 September 2016. Archived from the original on 9 September 2021. Retrieved 17 August 2021.
- ^ "Scalable Vector Graphics (SVG) 2". World Wide Web Consortium. 4 October 2018. Archived from the original on 19 July 2021. Retrieved 17 August 2021.
- ^ "Scalable Vector Graphics (SVG) 2". World Wide Web Consortium. 14 September 2025. Archived from the original on 10 February 2021. Retrieved 7 January 2024.
- ^ Alex, Danilo; Fujisawa, Jun (2002). "SVG as a Page Description Language". svgopen.org. Archived from the original on 29 May 2010. Retrieved 24 February 2010.
- ^ Paul, Festa (9 January 2003). "W3C releases scripting standard, caveat". CNet. Archived from the original on 17 May 2011. Retrieved 24 February 2010.
- ^ a b "SVG Tiny 1.2". Scalable Vector Graphics (SVG) Tiny 1.2 Specification. W3C. 22 December 2008. Archived from the original on 30 January 2014. Retrieved 5 March 2014.
- ^ "SVG in 3GPP Multimedia Messaging and Streaming Services (version March 2003)". SVG Open. 2003. Archived from the original on 26 June 2009. Retrieved 19 October 2009.
- ^ "3GPP Multimedia Messaging Service (MMS); Media formats and codecs (Release 5); 3GPP TS 26.140 V5.2.0 (2002-12); Technical Specification" (zipped doc). 3GPP. 2 January 2003. Archived from the original on 8 February 2007. Retrieved 25 February 2010.
- ^ "3rd Generation Partnership Project; Technical Specification Group Services and System Aspects; Multimedia Messaging Service (MMS); Media formats and codecs (Release 5)" (zipped doc). 3GPP TS 26.140 V5.2.0 (2002-12). 3GPP. March 2003. Archived from the original on 12 February 2007. Retrieved 24 February 2010.
- ^ "3GPP Specification detail - 3GPP TS 26.141: IP Multimedia System (IMS) Messaging and Presence; Media formats and codecs". 3GPP. 10 December 2009. Archived from the original on 7 October 2008. Retrieved 24 February 2010.
- ^ "Listing of phones that support SVG". Svg.org. Archived from the original on 8 January 2010. Retrieved 24 October 2010.
- ^ See www
.w3 which states, "SVG implementations must correctly support gzip-encoded [RFC 1952] and deflate-encoded [RFC 1951] data streams, for any content type (including SVG, script files, images).".org /TR /SVG11 /conform .html #ConformingSVGViewers - ^ "Saving compressed SVG (SVGZ)". SVG Zone. Adobe Systems. 14 July 2009. Archived from the original on 1 June 2010. Retrieved 24 February 2010.
- ^ For example, dev
.w3 .org /SVG /profiles /1 .1F2 /test /harness /htmlObject /conform-viewers-01-t .html - ^ "SVG specification, "Paths"". World Wide Web Consortium. 14 January 2003. Archived from the original on 21 June 2012. Retrieved 19 October 2009.
- ^ "SVG specification, "Basic Shapes"". World Wide Web Consortium. 14 January 2003. Archived from the original on 2 October 2009. Retrieved 19 October 2009.
- ^ "SVG specification, "Text"". World Wide Web Consortium. 14 January 2003. Archived from the original on 6 October 2009. Retrieved 19 October 2009.
- ^ "SVG specification, "Painting: Filling, Stroking and Marker Symbols"". World Wide Web Consortium. 14 January 2003. Archived from the original on 17 September 2009. Retrieved 19 October 2009.
- ^ "SVG specification, "Color"". World Wide Web Consortium. 14 January 2003. Archived from the original on 7 September 2009. Retrieved 19 October 2009.
- ^ "SVG specification, "Gradients and Patterns"". World Wide Web Consortium. 14 January 2003. Archived from the original on 21 September 2009. Retrieved 19 October 2009.
- ^ "IRC log of svg on 2008-11-17". W3C. 2008. Archived from the original on 10 October 2016. Retrieved 25 May 2009.
DS: Priorities should be layout, diffusion curves, 2.5D and make sure we work well with CSS on that
- ^ "Propositions for the next SVG spec". W3C. 16 March 2009. Archived from the original on 14 May 2011. Retrieved 25 May 2009.
Indeed, we do plan to add new gradient capabilities to SVG in the next version, and we are looking into diffusion curves, which I think will meet your needs ... *Diffusion curves* seems really a great idea.
- ^ Rusin, Zack (2008). "SVG in KDE: Freedom of Beauty". SVG Open. Archived from the original on 22 July 2009. Retrieved 25 May 2009.
- ^ Orzan, Alexandrina; Bousseau, Adrien; Winnemöller, Holger; Barla, Pascal; Thollot, Joëlle; Salesin, David (2008). "Diffusion Curves: A Vector Representation for Smooth-Shaded Images" (PDF). ACM Transactions on Graphics. 27. doi:10.1145/1360612.1360691. Archived (PDF) from the original on 18 June 2009. Retrieved 25 May 2009.
- ^ "Scalable Vector Graphics (SVG) 2, W3C Editor's Draft 13 June 2013". SVG WG. 2013. Archived from the original on 4 December 2013. Retrieved 17 September 2013.
- ^ "SVG specification, "Clipping, Masking and Compositing"". World Wide Web Consortium. 14 January 2003. Archived from the original on 1 December 2009. Retrieved 19 October 2009.
- ^ "SVG specification, "Filter Effects"". World Wide Web Consortium. 14 January 2003. Archived from the original on 28 August 2006. Retrieved 19 October 2009.
- ^ "SVG specification, "Interactivity"". World Wide Web Consortium. 14 January 2003. Archived from the original on 5 July 2019. Retrieved 19 October 2009.
- ^ "SVG specification, "Linking"". World Wide Web Consortium. 14 January 2003. Archived from the original on 25 June 2019. Retrieved 19 October 2009.
- ^ "SVG specification, "Scripting"". World Wide Web Consortium. 14 January 2003. Archived from the original on 1 October 2009. Retrieved 19 October 2009.
- ^ "SVG specification, "Animation"". World Wide Web Consortium. 14 January 2003. Archived from the original on 27 August 2006. Retrieved 19 October 2009.
- ^ "SVG specification, "Fonts"". World Wide Web Consortium. 14 January 2003. Archived from the original on 26 September 2009. Retrieved 19 October 2009.
- ^ "SVG specification, "Metadata"". World Wide Web Consortium. Archived from the original on 3 May 2009. Retrieved 19 October 2009.
- ^ Streichardt, Andreas (16 September 2003). "KDE Conquers the Vectors with KSVG". KDE News. Archived from the original on 30 June 2023. Retrieved 11 February 2012.
- ^ "Bug 276431 - external SVG not loaded from img tag". Mozilla. Archived from the original on 24 October 2012. Retrieved 9 November 2011.[text–source integrity?]
- ^ Lusotec (25 February 2009). "SVG image not shown by Firefox". mozilla.dev.tech.svg. Google Groups. Archived from the original on 14 May 2011. Retrieved 25 February 2010.
- ^ Brettz9 (25 August 2008). "SVG In HTML Introduction". Mozilla Developer Center. Mozilla. Archived from the original on 5 December 2008. Retrieved 25 February 2010.
- ^ Svensson, Peter (10 September 2008). "Creator of Web spots a flaw in Internet Explorer". NBC News. Associated Press. Archived from the original on 9 November 2013. Retrieved 25 February 2010.
- ^ "SVG in Firefox". Mozilla Developer Center. Mozilla. 23 October 2009. Archived from the original on 23 June 2008. Retrieved 25 February 2010.
- ^ "Mozilla SVG Status". Mozilla. Archived from the original on 5 March 2010. Retrieved 25 February 2010.
- ^ Mgjbot (15 January 2008). "SVG improvements in Firefox 3". Mozilla Developer Center. Mozilla. Archived from the original on 9 February 2014. Retrieved 25 February 2010.
- ^ "WebKit SVG Status". WebKit. 5 January 2010. Archived from the original on 10 February 2010. Retrieved 25 February 2010.
- ^ "Windows Internet Explorer 8 Expert Zone Chat (19 June 2008)". Microsoft. 19 June 2008. Archived from the original on 17 March 2010. Retrieved 24 October 2010.
- ^ Schiller, Jeff (13 February 2010). "SVG Support". Archived from the original on 16 February 2009. Retrieved 25 February 2010.
- ^ "What's New in Internet Explorer 9". Microsoft Developer Network. Microsoft. 22 March 2011. Archived from the original on 5 April 2011. Retrieved 22 March 2011.
- ^ "SVG (Windows)". Internet Explorer Dev Center. Microsoft. Archived from the original on 20 March 2014. Retrieved 27 August 2014.
- ^ "Microsoft Edge web platform features status and roadmap - Microsoft Edge Development". developer.microsoft.com. Archived from the original on 15 April 2018. Retrieved 19 April 2018.
- ^ "Get ready for plug-in free browsing". MSDN. 2014. Archived from the original on 31 December 2014. Retrieved 5 March 2014.
- ^ "SVG Open 2005 Conference and Exhibition - Proceedings - Cartoon Oriented User Interfaces". svgopen.org. Archived from the original on 3 December 2010. Retrieved 29 August 2010.
- ^ "Browser doesn't render SVG images". Archived from the original on 20 May 2011. Retrieved 1 January 2011.
- ^ "Firefox Mobile 4.0b2 (beta) for Android supports SVG images". Android Issue 1376. 16 December 2010. Archived from the original on 21 August 2014. Retrieved 29 January 2014.
- ^ "Support for SVG". RIM. Archived from the original on 10 October 2011. Retrieved 6 October 2011.
- ^ "BlackBerry Torch The HTML5 Developer Scorecard". Sencha. Archived from the original on 5 March 2014. Retrieved 6 October 2011.
- ^ "S60 Product info". S60.com. Archived from the original on 13 October 2007. Retrieved 19 October 2009.
- ^ "Nokia Releases Series 40 6th Edition Software Development Kit For World's Highest-Volume Mobile Developer Platform". www.fieldtechnologiesonline.com. Retrieved 12 June 2025.
- ^ Jezic, Damir (15–17 July 2002). "SVG for Embedded Systems". Zurich 2002. svgopen.org. Archived from the original on 16 March 2012. Retrieved 5 April 2012.
- ^ "eSVG". Intesis Intelligent Embedded Software. 2010. Archived from the original on 3 March 2012. Retrieved 29 January 2014.
- ^ Selinger, Peter (2001–2013). "Potrace – Transforming bitmaps into vector graphics". SourceForge project Potrace. Archived from the original on 9 September 2009. Retrieved 29 January 2014.
- ^ "What's new in PowerPoint for Microsoft 365". support.microsoft.com. September 2019. Archived from the original on 13 March 2021. Retrieved 17 April 2021.
- ^ Nguyen, Thanh Nguyen (7 November 2019). "Anatomy of Scalable Vector Graphics (SVG) Attack Surface on the Web". Fortinet Blog. Archived from the original on 21 February 2023. Retrieved 21 February 2023.
- ^ a b "SVG Security - W3C Wiki". W3C. Archived from the original on 21 February 2023. Retrieved 21 February 2023.
- ^ Concolato, Cyril (July 2005). "MPEG-4 LASeR white paper". International Organization for Standardization. Archived from the original on 25 July 2011. Retrieved 29 August 2010.
- ^ "ISO/IEC 14496-20:2008 - Information technology – Coding of audio-visual objects – Part 20: Lightweight Application Scene Representation (LASeR) and Simple Aggregation Format (SAF)". International Organization for Standardization. Archived from the original on 14 May 2011. Retrieved 30 October 2009.
- ^ "LASeR - the MPEG standard for Rich Media Services" (PDF). Archived (PDF) from the original on 21 February 2011. Retrieved 11 April 2010.
- ^ Chiariglione, Leonardo (8 March 2005). "Riding the media bits - Bits and bytes". Archived from the original on 25 September 2010. Retrieved 30 October 2009.
External links
[edit]- W3C SVG page specifications, list of implementations
- W3C SVG primer W3C Primer (draft) under auspices of SVG Interest Group
- MDN - SVG: Scalable Vector Graphics
Introduction
Definition and Purpose
Scalable Vector Graphics (SVG) is an XML-based markup language for describing two-dimensional vector graphics, which can include mixed vector and raster elements, and supports interactivity and animation capabilities.[1] It allows for the creation of graphics that are stylable with CSS and scriptable with languages like JavaScript, enabling dynamic content.[4] As an open standard developed by the World Wide Web Consortium (W3C), SVG facilitates embedding directly into HTML documents, making it integral to web-based applications and documents.[3] The primary purpose of SVG is to produce scalable icons, logos, charts, and diagrams that maintain sharpness and clarity at any resolution or zoom level, without pixelation, due to its vector nature.[1] This scalability supports its use in diverse contexts, from web interfaces to high-resolution printing. Additionally, SVG's text-based format promotes web accessibility by allowing screen readers to interpret descriptive elements and benefits search engine optimization (SEO) through indexable text content within the graphics. SVG was first established as a W3C Recommendation in September 2001 with version 1.0, marking it as a foundational open standard for vector graphics on the web.[7] Common use cases include data visualization for interactive charts, user interface elements like buttons and icons, and print-ready illustrations that adapt seamlessly across digital and physical media.[4] Subsequent evolution, such as SVG 2, has enhanced these features for broader interoperability.[1]Key Advantages
Scalable Vector Graphics (SVG) offers resolution independence, allowing images to scale infinitely without loss of quality, which makes it particularly suitable for responsive web design and high-DPI displays such as Retina screens. Unlike raster formats like PNG or JPEG, which pixelate when enlarged, SVG maintains crisp edges through its vector-based definitions, ensuring consistent rendering across devices and zoom levels.[8] SVG files achieve smaller sizes for complex graphics compared to equivalent raster images because they use mathematical descriptions of shapes, paths, and colors rather than storing pixel data.[9] This parametric approach—defining elements via coordinates and formulas—results in compact representations that compress efficiently, reducing bandwidth needs while preserving detail for intricate diagrams or icons. As a text-based XML format, SVG is inherently editable with standard text editors or integrated development environments, facilitating direct modifications without specialized software.[10] This structure also enables programmatic manipulation through languages like JavaScript, allowing dynamic updates to elements at runtime, and supports version control systems such as Git due to its plain-text nature.[5] SVG provides built-in accessibility features, including support for WAI-ARIA attributes that convey semantic roles, states, and descriptions to assistive technologies like screen readers.[11] For instance, attributes such asaria-label and role can describe graphical elements, making charts or icons interpretable for users with disabilities, while the text-based format enhances searchability by allowing content to be indexed by search engines.[12]
The format natively supports interactivity, such as hover effects via CSS pseudo-classes and animations through integrated SMIL or CSS transitions, enabling responsive behaviors without external plugins. This built-in capability allows developers to create engaging user experiences, like tooltips on mouseover or smooth scaling transitions, directly within the SVG document.
History
Early Development and SVG 1.0
The development of Scalable Vector Graphics (SVG) originated in the mid-1990s as part of the World Wide Web Consortium's (W3C) efforts to establish an open standard for vector graphics on the web, driven by the need for scalable, resolution-independent imagery amid the limitations of raster formats and proprietary technologies like Macromedia Flash.[13][2] In 1996, W3C chair Chris Lilley published requirements for scalable graphics, emphasizing resizability for varying display densities, improved print quality, and enhanced interactivity to address the growing demand for dynamic web content without relying on closed formats.[13] This initiative gained momentum in 1998 when the W3C chartered the SVG Working Group, involving key contributors from industry leaders including Adobe Systems, Microsoft, IBM, Sun Microsystems, and others, to create a unified XML-based language that combined elements from competing proposals such as Adobe's Precision Graphics Markup Language (PGML) and Microsoft's Vector Markup Language (VML).[2][14] The SVG Working Group aimed to provide an open alternative to proprietary vector solutions, focusing on web integration, accessibility, and extensibility through XML syntax.[15] The first public working draft of SVG was released on February 11, 1999, outlining a specification for two-dimensional vector and mixed vector/raster graphics with support for basic shapes, paths, text, gradients, and styling via CSS.[15] Following iterative reviews and last-call drafts, including the eighth working draft on March 3, 2000, SVG advanced to Candidate Recommendation status on August 2, 2000, marking a significant milestone toward standardization.[16] SVG 1.0 was formally published as a W3C Recommendation on September 4, 2001, establishing foundational features such as a user coordinate system for precise positioning, viewport definitions for scalable rendering across devices, and seamless integration with XHTML for embedding graphics in web documents.[7] These elements enabled developers to create resolution-independent illustrations, diagrams, and interfaces without pixelation, while supporting hyperlinking and basic interactivity.[7] Key goals included promoting interoperability through open standards and fostering adoption in web authoring tools, though early implementations relied on plugins like Adobe's SVG Viewer released in late 2001.[16][17] Despite these advancements, SVG 1.0 faced significant early adoption challenges due to limited native browser support; for instance, while Mozilla provided partial rendering by 2003, Internet Explorer required external viewers until version 9 in 2011, delaying widespread use until the mid-2000s.[18][19] This reliance on plugins and inconsistent implementations across platforms initially hindered SVG's penetration in web development, though it laid the groundwork for future modular profiles in subsequent versions.[16]SVG 1.1 Standardization
SVG 1.1 was published as a W3C Recommendation on January 14, 2003, marking a significant maturation of the Scalable Vector Graphics standard from its initial 1.0 version.[20] This release focused on stabilizing and expanding the core specification to better support diverse implementation needs while preserving foundational vector graphics capabilities. A second edition followed on August 16, 2011, primarily to incorporate errata corrections and clarifications without introducing new features.[21] Key enhancements in SVG 1.1 included full support for CSS styling, allowing developers to apply presentation attributes more flexibly across elements.[22] It also provided robust DOM manipulation interfaces for dynamic content modification and integrated animation capabilities through SMIL, enabling declarative timing and synchronization of visual effects. Scripting interfaces were refined to facilitate JavaScript interactions, enhancing interactivity within SVG documents. Additionally, the specification defined over 100 elements, ranging from basic shapes and paths to advanced features like filters and gradients, while ensuring backward compatibility with SVG 1.0 content.[3] To address varying device constraints, SVG 1.1 introduced modularization, dividing the language into profiles such as SVG Tiny for resource-limited mobile devices, SVG Basic for intermediate capabilities, and SVG Full for comprehensive desktop support.[23] This approach allowed tailored implementations without compromising the core standard's integrity.[24] Adoption accelerated with native browser integration, notably in Firefox 1.5 released in November 2005, which provided broad SVG rendering support.[25] Microsoft followed with partial SVG support in Internet Explorer 9 in March 2011, broadening accessibility.[6] These milestones contributed to SVG's growth in web applications, particularly for scalable maps and interactive infographics, where its vector precision and dynamic features proved advantageous.[26]SVG 2 and Ongoing Evolution
The development of SVG 2 began with its first Working Draft published by the W3C on 28 August 2012, building directly on the SVG 1.1 Second Edition to address usability gaps and incorporate community feedback.[27] As of November 16, 2025, the specification remains in Editor's Draft status, with ongoing refinements but no advancement to full W3C Recommendation due to dependencies on broader participation and implementation testing. Some proposed features, such as hatching patterns and direct embedding of HTML elements like <canvas>, <video>, and <audio> without <foreignObject>, have been removed due to lack of interest in implementation.[28][29] SVG 2 introduces several key enhancements to streamline authoring and rendering. Native support for CSS transforms allows thetransform attribute to apply to any element, including the root <svg>, treating it as a presentation attribute compatible with CSS Transforms Module Level 1 for consistent 2D manipulations. This feature is supported in Chrome 137 and later (as of May 2025). Text-on-path functionality improves by permitting the <textPath> element to directly reference path data via a path attribute, simplifying curve-based text layout without external <path> dependencies.[30] Overflow handling is refined to support scrollbars via overflow: scroll on <svg> elements, removing the default overflow: hidden behavior for better viewport control in embedded contexts.[31]
Animation capabilities shift away from the deprecated SMIL (Synchronized Multimedia Integration Language) module, which is no longer part of SVG 2, toward integration with CSS Animations and Web Animations API for more performant, scriptable effects aligned with modern web standards.[1] SVG 2 facilitates deeper ties with HTML5 technologies, though embedding HTML content still requires <foreignObject>.[30]
Browser implementations remain partial, with features like enhanced transforms available in recent versions of Chrome (137+), though full interoperability lags behind due to the draft status.[32] The W3C SVG Working Group continues iterative updates, with goals for Proposed Recommendation status hinging on increased testing and adoption, potentially targeting completion around 2026 amid calls for renewed focus on specification maturity.[33]
Accessibility receives targeted improvements, including native support for tabindex to enable keyboard navigation and WAI-ARIA attributes like aria-label and role for semantic mapping of graphics to screen readers.[34] Better focus indicators are mandated through user-agent stylesheets that render visible outlines on interactive elements, ensuring compliance with WCAG guidelines for perceivable navigation in vector content.
Core Design Principles
XML-Based Syntax
Scalable Vector Graphics (SVG) is defined as an XML-based language for describing two-dimensional vector graphics, adhering to the XML 1.0 specification for syntax and structure.[35] As such, SVG documents must be well-formed XML, utilizing the SVG namespace identified by the URIhttp://www.w3.org/2000/svg to ensure proper element and attribute recognition in XML parsers.[36] This namespace is declared using the xmlns attribute on the root element, such as xmlns="http://www.w3.org/2000/svg", in compliance with the Namespaces in XML recommendation.
The foundational structure of an SVG document centers on the <svg> root element, which establishes the canvas for graphics content.[36] Key attributes of the <svg> element include width and height, which specify the intrinsic dimensions of the viewport—defaults to auto or 100% for embedded contexts—and viewBox, which defines a coordinate system for scaling content independently of resolution.[36] The viewBox attribute, for instance, enables the scalability principle by mapping logical coordinates to the physical viewport.[37] Nested <svg> elements can be used for grouping or modularization, each with their own attributes like x and y for positioning in embedded scenarios.[36]
SVG documents can be embedded in web pages either inline within HTML using the <svg> tag, where the namespace is implicitly applied by HTML parsers, or as external files with the .svg extension referenced via the <img> element (treating it as an image with MIME type image/svg+xml) or the <object> element for more interactive integration.[35] External SVG files must include an explicit XML declaration like <?xml version="1.0" encoding="UTF-8"?> and the namespace attribute to ensure compatibility across parsers.[36]
For validity, SVG documents are validated against the SVG Document Type Definition (DTD) for SVG 1.1 or the RelaxNG schema for SVG 2, confirming adherence to the language's element hierarchy and attribute constraints.[38][1] Malformed XML, such as unclosed tags or invalid namespace declarations, results in parsing errors; user agents are required to treat non-well-formed SVG as non-conforming and may ignore erroneous sections or fail to render the document entirely, per XML processing rules.[39]
A minimal valid SVG document illustrating the basic structure might draw a simple rectangle, as shown below:
<?xml version="1.0" encoding="UTF-8"?>
<svg width="100" height="100" viewBox="0 0 100 100"
xmlns="http://www.w3.org/2000/svg">
<rect x="10" y="10" width="80" height="80" fill="blue"/>
</svg>
<?xml version="1.0" encoding="UTF-8"?>
<svg width="100" height="100" viewBox="0 0 100 100"
xmlns="http://www.w3.org/2000/svg">
<rect x="10" y="10" width="80" height="80" fill="blue"/>
</svg>
Scalability and Resolution Independence
SVG achieves scalability through its vector-based rendering, where graphics elements such as paths and shapes are defined mathematically using coordinates rather than raster pixels. This approach allows for precise descriptions of lines, curves, and fills via elements like<path>, <rect>, and <circle>, which specify positions and dimensions in a coordinate system independent of the output device's resolution. As a result, SVG images can be scaled infinitely without introducing jagged edges or loss of detail, as the rendering engine recalculates the geometry at any size.[1]
A core mechanism enabling this scalability is the distinction between the viewport and the viewBox. The viewport represents the physical display area available for rendering the SVG content, determined by the embedding context such as an HTML <img> tag or CSS styling. In contrast, the viewBox attribute on the root <svg> element defines a logical coordinate system by specifying a rectangular region (e.g., viewBox="0 0 100 100"), which maps the SVG's internal coordinates to the viewport. This mapping facilitates zooming and panning without artifacts, as the content is transformed proportionally to fit the viewport, preserving the vector nature of the graphics.[1]
SVG supports a variety of units to accommodate both relative and absolute sizing, further enhancing its resolution independence. User units serve as the default, treated as abstract coordinates that scale with the viewBox, while percentages are relative to the immediate parent's viewport or the viewBox itself. Font-relative units like em (relative to the font's em square) and ex (relative to the x-height) allow text and graphics to adapt to typographic contexts. Absolute units such as px (pixels, approximately 1/96 inch), in (inches), and others like cm or mm ensure consistent sizing across print and digital media. These units enable SVG to maintain proportions across different devices without manual adjustments.[1]
Resolution independence is particularly valuable in responsive web designs, where SVG graphics automatically scale to fit varying screen sizes and density. For instance, applying CSS properties like width: 100%; height: auto; to an <svg> element causes it to resize fluidly within its container, leveraging the vector definitions to render crisply on high-DPI displays without pixelation. This behavior integrates seamlessly with CSS media queries, allowing SVGs to adapt to breakpoints (e.g., adjusting sizes for mobile versus desktop) while preserving quality, unlike bitmap formats that require multiple versions.[1]
The preserveAspectRatio attribute on the <svg> or <symbol> elements ensures aspect ratio preservation during scaling, preventing distortion when the viewport dimensions differ from the viewBox. By default set to xMidYMid meet, it scales the content uniformly to fit within the viewport while centering it and maintaining the original proportions; alternatives like xMidYMid slice fill the viewport by cropping excess content if needed. This attribute is essential for logos, icons, and diagrams, guaranteeing consistent visual fidelity across resizes.[1]
Integration with Web Technologies
SVG integrates seamlessly with HTML5, allowing it to be embedded directly as an inline element within HTML documents using the<svg> tag, which places the SVG content as part of the page's structure without requiring external files.[40] This inline approach enables SVG to participate fully in the HTML document flow, supporting CSS styling and layout properties like flexbox or grid. Alternatively, SVG can be embedded externally using the <iframe> element for isolated rendering within a dedicated browsing context, or the <object> element for embedding as a replaceable resource, which provides fallback content if the SVG fails to load.[41] These methods ensure SVG's versatility in web pages, from simple icons to complex diagrams.
When embedded inline, SVG elements become part of the overall HTML Document Object Model (DOM), allowing direct manipulation through standard JavaScript APIs such as document.getElementById() to access and modify SVG nodes alongside HTML elements. This unified DOM integration facilitates dynamic updates, such as altering attributes or styles, without namespace switching, enhancing SVG's role in interactive web applications.[36]
SVG can hybridize with the HTML <canvas> element for performance optimization, where an SVG image or inline SVG can be rasterized onto a canvas using the drawImage() method to convert vector content to pixels for further manipulation or export. Conversely, canvas-generated raster data can inform dynamic SVG creation, such as by serializing pixel information into vector paths via JavaScript, though this often requires additional processing for true vector fidelity. This combination leverages SVG's precision for design and canvas's speed for rendering intensive scenarios.
To support accessibility, inline SVG uses ARIA attributes like role="img" to indicate it functions as an image, paired with <title> and <desc> elements for descriptive text that screen readers announce.[11] For externally embedded SVG via <img> or <object>, the hosting HTML element provides alt text for equivalent purpose, ensuring compatibility with assistive technologies like screen readers that traverse the DOM. Role attributes such as role="graphics-document" further guide interpretation of complex SVGs as documents, promoting inclusive web experiences.
For optimized web delivery, SVGz format applies gzip compression to SVG files, reducing size by 20-50% while maintaining the .svgz extension and MIME type image/svg+xml for browser recognition.[42] This compression is particularly effective for text-heavy SVG, minimizing bandwidth without altering content, and servers can enable it transparently for HTTP transfers.
Graphics Elements
Basic Shapes and Paths
SVG's basic shapes form the foundational building blocks for constructing simple geometric figures directly within the document, enabling efficient rendering of common primitives like rectangles and circles without relying on more verbose path definitions. These elements are defined using straightforward attributes that specify position, size, and orientation in the user coordinate system, where coordinates are typically expressed in user units that map to the viewport. All basic shapes support filling and stroking to define their visual appearance, which can be applied via presentation attributes or external stylesheets.[43] The<rect> element creates an axis-aligned rectangle or rounded rectangle. Key attributes include x and y for the upper-left corner position (defaulting to 0), width and [height](/page/Height) for dimensions (must be positive lengths), and optional rx and ry for horizontal and vertical corner radii (defaulting to 0 and clamped to half the width or height if larger). For instance, the syntax <rect x="10" y="10" width="100" [height](/page/Height)="100" rx="20"/> draws a square with rounded corners starting at coordinates (10,10). If width or height is zero or negative, the element does not render.[44]
Circles and ellipses provide circular geometry. The <circle> element uses cx and cy for the center (default 0) and r for the radius (must be positive). An example is <circle cx="50" cy="50" r="40"/>, which renders a circle centered at (50,50) with radius 40; a zero or negative radius prevents drawing. The <ellipse> element extends this with separate rx and ry radii for the x and y directions, such as <ellipse cx="0" cy="0" rx="80" ry="50"/> for an oval shape aligned with the axes. Both elements outline the shape starting from the "3 o'clock" position and proceed counterclockwise.[45][46]
Linear elements handle straight-line geometry. The <line> element connects two points with attributes x1, y1 (start, default 0) and x2, y2 (end, default 0), as in <line x1="0" y1="0" x2="100" y2="100"/>; it cannot be filled since it has no enclosed area. For multi-segment lines, <polyline> uses a points attribute listing coordinate pairs (e.g., "0,0 50,100 100,0"), creating an open path that connects the points in order without closing. In contrast, <polygon> closes the shape by connecting the last point to the first, suitable for filled polygons, with the same points format like "100,10 40,198 190,78 10,78 160,198". Both polyline and polygon points are interpreted in user space, and invalid coordinates (e.g., non-numeric) cause parsing errors.[47][48][49]
For intricate or irregular geometry beyond basic primitives, the <path> element employs a compact path data syntax in the d attribute to define outlines using a sequence of commands and coordinates, simulating a pen that moves and draws like in vector graphics editors. Path data supports subpaths, each starting with a moveto command, and can be filled, stroked, or used for clipping; the current point tracks the pen's position after each operation. Commands are case-sensitive: uppercase for absolute coordinates (relative to the origin) and lowercase for relative offsets from the current point. Numbers can include decimals, exponents, or scientific notation, and commas or whitespace separate values.[50][51]
Path commands include lineto variants for straight segments: L or l (x y) draws to the specified point, H or h (x) for horizontal, and V or v (y) for vertical, with multiple coordinates allowed per command (e.g., "L 100 100 200 200"). Curves are achieved via Bézier commands; the cubic Bézier C or c (x1 y1 x2 y2 x y) uses two control points to define smooth bends, while the smooth variant S or s (x2 y2 x y) reflects the second control point of the previous curve for continuity. Quadratic Bézier curves use Q or q (x1 y1 x y) with one control point, and T or t (x y) for smooth joins by reflection. Arcs are drawn with A or a (rx ry x-axis-rotation large-arc-flag sweep-flag x y), specifying elliptical parameters: radii, rotation angle, flags to choose the larger arc (0/1) and direction (0 for negative-angle, 1 for positive), ending at (x,y); degenerate ellipses (rx or ry ≤ 0) are adjusted to lines. The Z or z command closes the current subpath with a straight line to the starting point, without advancing the current point.[52][53][54][55][56]
A practical example of path data constructs a simple irregular pentagon using moveto, lineto, and closepath commands:
<path d="M 100 100 L 150 50 L 200 100 L 170 150 L 130 150 Z" />
<path d="M 100 100 L 150 50 L 200 100 L 170 150 L 130 150 Z" />
d attribute strings across multiple lines (recommended under 255 characters per line) to aid parsing and tool compatibility, though SVG viewers must handle concatenated data correctly. Simplification techniques, such as reducing unnecessary commands or approximating curves with fewer segments, can further minimize data length without visual loss, improving rendering efficiency in resource-constrained environments.[51]
Text and Typography
SVG's text rendering is achieved through dedicated elements that allow for precise placement and styling of character strings within vector graphics. The primary<text> element defines a block of text at specified coordinates, rendering the content as a single inline sequence without inherent line wrapping unless configured otherwise. This element supports international text processing, including bidirectional layouts for scripts like Arabic and Hebrew, following the Unicode bidirectional algorithm. Positioning is controlled via attributes such as x and y for absolute user-space coordinates, and dx and dy for incremental relative offsets from the prior glyph's position, enabling fine-grained layout adjustments. Alignment is further refined with text-anchor for horizontal positioning (values: start, middle, end) and dominant-baseline for vertical baseline selection (e.g., alphabetic, middle), ensuring consistent rendering across diverse typographic traditions.[58]
Within a <text> element, the <tspan> sub-element facilitates segmented styling and positioning, acting as an inline container for portions of the text string. It inherits the parent <text>'s attributes but allows overrides, such as localized x, y, dx, or dy values to shift specific spans, supporting complex layouts like nested emphasis or kerning tweaks without breaking the overall flow. For font integration, SVG leverages CSS properties like font-family, font-size, font-style, and font-weight, applied via stylesheets or inline attributes. Custom fonts are incorporated using the CSS @font-face rule to reference external files, such as WOFF or WOFF2 formats, with fallback mechanisms provided by comma-separated lists in font-family (e.g., a primary custom font followed by generic families like serif or sans-serif if the primary fails to load). This ensures robust rendering, as user agents substitute available system fonts when specified resources are unavailable, aligning with CSS font matching rules.[58][59]
A specialized feature for curved text is the <textPath> element, which places text along the outline of a referenced <path> element, using the xlink:href attribute to link to the path's ID. This enables artistic effects like text following arcs or irregular contours, with layout governed by path length and glyph orientation rules that rotate characters tangent to the path's direction. Additional attributes like startOffset control the initial positioning along the path (as a percentage or length), while method (align or stretch) and spacing (auto or exact) dictate how glyphs fit the contour, preserving readability for applications such as logos or diagrams.[58]
SVG 2 introduces enhancements for more advanced typography, particularly in handling multiline and vertical text. The <text> element now supports automatic line wrapping through the inline-size CSS property, which defines a rectangular content area for reflow, and the shape-inside property for wrapping around custom SVG shapes, improving support for paragraph-like layouts. Vertical writing modes are better accommodated via the writing-mode property (e.g., vertical-rl for right-to-left vertical flow), integrated with CSS Writing Modes Level 3, allowing seamless rendering of scripts like CJK ideographic text with appropriate glyph rotation and baseline adjustments. Further refinements include the textLength attribute for forcing text to a desired length via scaling or spacing (lengthAdjust), and properties like text-overflow for ellipsis on truncated lines, enhancing usability in responsive designs. Font integration in SVG 2 aligns more closely with CSS Fonts Level 3, mandating WOFF support for OpenType features such as ligatures, while deprecating legacy SVG fonts in favor of external web fonts with robust fallbacks.[60][59]
Images and Linking
SVG graphics can incorporate external raster images through the<image> element, which references files such as PNG or JPEG via the href attribute (or the deprecated xlink:href in earlier versions).[61] This element positions the image within a specified rectangle defined by x, y, width, and height attributes, rendering it in the current user coordinate system.[61] The preserveAspectRatio attribute controls how the image scales and aligns within the viewport, with values like xMidYMid meet preserving the aspect ratio while fitting the image to the rectangle, or none allowing distortion to fill the space exactly.[62] For example, the following embeds a PNG image:
<image x="10" y="10" width="100" height="100" href="example.png" preserveAspectRatio="xMidYMid meet"/>
<image x="10" y="10" width="100" height="100" href="example.png" preserveAspectRatio="xMidYMid meet"/>
href attribute replaces xlink:href and aligns with HTML conventions, while supporting features like CORS via the crossorigin attribute for secure cross-origin fetches.[61]
To promote reusability and efficiency, the <use> element allows referencing and instantiating previously defined SVG content, such as shapes or groups stored in <defs> or <symbol> elements.[63] The href attribute points to the target element by ID (e.g., #shapeId) or an external URL, creating a non-editable clone that inherits styles from the <use> context and responds to events as if it were the original.[63] Positioning and scaling are handled by x, y, width, and height on the <use> element, particularly useful for symbols in <symbol> which define reusable viewports.[64] An example reuses a defined circle:
<defs>
<circle id="myCircle" cx="50" cy="50" r="40" fill="blue"/>
</defs>
<use href="#myCircle" x="100" y="100"/>
<defs>
<circle id="myCircle" cx="50" cy="50" r="40" fill="blue"/>
</defs>
<use href="#myCircle" x="100" y="100"/>
<a> element, which wraps graphical content to enable navigation upon user interaction, such as clicking.[65] The href attribute specifies the target URL, supporting both internal fragment identifiers (e.g., #sectionId) and external destinations, while attributes like target control the opening context (e.g., _blank for a new window).[66] For instance, wrapping a rectangle to link to an external site:
<a href="https://example.com" target="_blank">
<rect x="10" y="10" width="100" height="50" fill="green"/>
</a>
<a href="https://example.com" target="_blank">
<rect x="10" y="10" width="100" height="50" fill="green"/>
</a>
<a> element integrates seamlessly with other SVG features, allowing links on text, paths, or groups, and follows standard URL processing rules.[65]
External references in SVG, via href in elements like <image>, <use>, or <a>, enable linking to other SVG files or resources using absolute or relative URLs, including fragment identifiers to target specific elements (e.g., other.svg#elementId).[67] This facilitates modular designs, such as embedding sub-documents or navigating between files, with the XLink namespace (http://www.w3.org/1999/xlink) used in SVG 1.1 for xlink:href to denote linking semantics.
However, external links introduce security considerations, as they can fetch unauthorized resources or enable unintended data exposure if not restricted by user agents.[68]
Styling and Rendering
CSS and Attribute Styling
SVG elements can be styled using presentation attributes directly on the elements or through CSS rules, allowing for flexible control over visual properties such as color, line thickness, and transparency.[69] Presentation attributes, likefill, stroke, stroke-width, and opacity, are XML attributes that specify styles inline, functioning as CSS properties with values parsed according to CSS rules.[70] For instance, a rectangle element might be defined as <rect width="100" height="50" fill="blue" stroke="black" stroke-width="2" opacity="0.8"/>, where fill sets the interior color, stroke the outline color, stroke-width the outline thickness, and opacity the overall transparency. The stroke-dasharray attribute can customize the stroke pattern, such as creating a dashed line with stroke-dasharray="10,5", which specifies alternating segments of 10 units on and 5 units off; this is equivalently applied via CSS, for example circle { stroke-dasharray: 10,5; } on a filled circle to produce a red dashed outline around a yellow interior.[71][72] These attributes contribute to the author level in the CSS cascade but hold lower specificity (0), making them easy to override.[73]
CSS styling integrates seamlessly with SVG, enabling the use of selectors to target elements, such as svg circle { fill: [red](/page/Red); } to color all circles red within an SVG, or more specific rules like .shape:hover { stroke: green; } for interactive states triggered by user events.[74] Styles inherit from parent elements, including from surrounding HTML, allowing SVG to blend with web page layouts—for example, a div with color: [navy](/page/Navy) can pass that value to child SVG text via the fill property if not overridden. External stylesheets, inline <style> elements, or the style attribute can declare these rules, with CSS properties like fill and stroke applying identically to SVG as to other elements.[69]
In the CSS cascade, presentation attributes are treated as author-origin declarations but yield to CSS rules from stylesheets or inline styles with higher specificity or later declaration order; for example, a CSS rule rect { fill: green !important; } will override an attribute's fill="blue".[75] The !important declaration can further enforce precedence in CSS but is invalid in presentation attributes themselves.[70] This hierarchy ensures that declarative CSS maintains control over inline attributes, promoting maintainable designs.
SVG introduces specific properties for precise rendering control, such as vector-effect, which modifies how transformations affect elements—for instance, vector-effect: non-scaling-stroke prevents stroke width from scaling during zooms or resizes on paths and shapes.[76] Similarly, clip-path defines a clipping region using an SVG <clipPath> element or basic shapes, restricting visibility to within that boundary, as in clip-path: url(#myClip); referencing a defined path.[77] These properties can be set via attributes or CSS, enhancing SVG's vector nature without altering underlying geometry.
A practical example involves styling a path element with a CSS class for dynamic effects:
<svg width="200" height="100">
<style>
.path-line {
fill: none;
stroke: blue;
stroke-width: 2;
}
.path-line:hover {
stroke: red;
stroke-width: 4;
}
</style>
<path class="path-line" d="M10 50 Q 100 10 190 50" />
</svg>
<svg width="200" height="100">
<style>
.path-line {
fill: none;
stroke: blue;
stroke-width: 2;
}
.path-line:hover {
stroke: red;
stroke-width: 4;
}
</style>
<path class="path-line" d="M10 50 Q 100 10 190 50" />
</svg>
Gradients, Patterns, and Filters
SVG provides mechanisms for creating complex visual effects through gradients, patterns, and filters, which extend basic solid color fills to enable smooth color transitions, repetitive textures, and post-processing modifications to graphical elements.[78] These features are defined as reusable paint servers or filter resources within the<defs> element, allowing them to be referenced by ID across the document for efficient rendering.[78]
Gradients in SVG enable smooth color interpolations between multiple points, using the <linearGradient> and <radialGradient> elements. A linear gradient is specified by defining start and end points via attributes such as x1, y1, x2, and y2, with color transitions controlled by child <stop> elements that set offset, stop-color, and stop-opacity values ranging from 0 to 1 (or percentages).[79] For example, a simple linear gradient might be defined as:
<linearGradient id="linearGrad">
<stop offset="0%" stop-color="blue"/>
<stop offset="100%" stop-color="red"/>
</linearGradient>
<linearGradient id="linearGrad">
<stop offset="0%" stop-color="blue"/>
<stop offset="100%" stop-color="red"/>
</linearGradient>
fill="url(#linearGrad)" or stroke="url(#linearGrad)", with options for coordinate units (gradientUnits) and transformations (gradientTransform) to adjust orientation and scaling.[79] Radial gradients, defined with <radialGradient>, use center points (cx, cy), radii (r, fr), and focal points (fx, fy) to create elliptical or circular fades, similarly populated with <stop> elements.[80] In SVG 2, mesh gradients are introduced via <meshGradient>, employing bicubic patches (Coons patches) for more sophisticated, non-linear color blending across irregular surfaces, enhancing capabilities for realistic shading.[81]
Patterns allow for tiled fills using the <pattern> element, which defines a reusable graphic—such as paths, shapes, or even other gradients—that repeats across a specified area. Key attributes include x, y, width, height for the tile bounds, patternUnits for coordinate scaling, and patternTransform for rotation or skewing.[82] For instance:
<pattern id="tilePattern" width="50" height="50">
<circle cx="25" cy="25" r="20" fill="green"/>
</pattern>
<pattern id="tilePattern" width="50" height="50">
<circle cx="25" cy="25" r="20" fill="green"/>
</pattern>
fill="url(#tilePattern)", supporting complex, non-uniform textures while maintaining vector scalability. SVG 2 extends patterns with support for external references via href and hatch patterns for simple stroked lines.[82]
Filters provide image-processing effects through the <filter> element, which contains primitive operations applied to source graphics before compositing. Filters are referenced using the filter="url(#filterID)" attribute on target elements, with the filter region bounded by x, y, width, and height attributes.[83] Common primitives include <feGaussianBlur>, which applies a Gaussian kernel blur controlled by stdDeviation (e.g., stdDeviation="5" for moderate softening), useful for glows or softening edges.[84] Color adjustments are handled by <feColorMatrix>, which uses a 5x4 transformation matrix or predefined types like saturate or hueRotate to modify RGB channels, enabling effects such as grayscale conversion.[85] Shadows are created with <feDropShadow>, combining offset (dx, dy) and blur (stdDeviation) on the alpha channel.[86] Morphological operations via <feMorphology> perform dilation or erosion with a specified radius and operator, altering shape boundaries for thickening or thinning outlines.[87] For procedural textures, SVG's <feTurbulence> primitive generates Perlin noise patterns, configurable with baseFrequency for scale, numOctaves for detail layers (up to 10 typically), and type as fractalNoise for smooth variations or turbulence for sharper contrasts, simulating natural phenomena like clouds or water.[88] These primitives chain together within a single <filter>, processing inputs like SourceGraphic or SourceAlpha to produce layered effects while preserving SVG's resolution independence.[89]
Transformations and Coordinate Systems
In SVG, coordinate systems define the spatial context for rendering graphics, distinguishing between the viewport coordinate system, which establishes the initial rendering region, and the user coordinate system, which maps abstract units to that viewport and can be modified by transformations.[37] The viewport is a rectangular area determined by the dimensions of the embedding element, such as an<svg> tag's width and height attributes, with its origin typically at the top-left corner and positive x-axis to the right and y-axis downward.[90] In contrast, user space starts identical to the viewport but allows scaling, translation, and rotation through the viewBox attribute or the transform property, enabling resolution-independent positioning that builds on SVG's vector scalability foundations.[91] Object space refers to the local coordinate system of individual elements, such as the bounding box of a path before any transformations are applied, which is crucial for relative positioning in attributes like gradients.[92]
The transform attribute, or equivalently the CSS transform property, applies 2D affine transformations to elements, groups, or the entire SVG, altering their position, size, or orientation relative to the current user space.[93] Common transformation functions include translate(tx [ty]) for shifting by tx units along the x-axis (and ty along y if specified, defaulting to 0); scale(sx [sy]) for uniform or non-uniform scaling (sy defaults to sx); rotate(angle [cx cy]) for rotation by angle degrees around the point (cx, cy) if provided, otherwise the origin; skewX(angle) and skewY(angle) for shearing along the respective axes; and matrix(a b c d e f) for a general 2D affine transformation.[94] These can be chained in a single transform list, composing via matrix multiplication where later transformations are post-multiplied to earlier ones, forming a cumulative current transformation matrix (CTM) that maps user coordinates to viewport coordinates.[95]
The viewBox attribute on the root <svg> element or nested <svg> viewports establishes the initial user coordinate system by defining a rectangular region (min-x min-y width height) that is scaled and translated to fit the viewport, preserving aspect ratio via the preserveAspectRatio attribute to ensure uniform scaling.[91] For instance, viewBox="0 0 100 100" maps a 100x100 unit abstract space to the actual viewport dimensions, allowing content to scale responsively without distortion.[91] In nested SVGs, such as an inner <svg x="25%" y="25%" width="50%" height="50%">, coordinates are relative to the parent viewport's user space unless overridden by a local viewBox or transform, enabling modular, hierarchical layouts.[96]
At its core, SVG's transformations rely on 2D affine mathematics, where each operation corresponds to a 3x3 matrix of the form , preserving parallelism and ratios but not angles or lengths unless orthogonal.[97] Composition occurs by multiplying these matrices in reverse order of application (post-multiplication), allowing complex effects like combined scaling and rotation without recalculating coordinates manually.[95] For example, applying rotate(45) to a <g> group element rotates all child shapes 45 degrees counterclockwise around the current origin:
<g transform="rotate(45)">
<rect x="10" y="10" width="80" height="80" fill="blue"/>
</g>
<g transform="rotate(45)">
<rect x="10" y="10" width="80" height="80" fill="blue"/>
</g>
Interactivity and Animation
Scripting with JavaScript
SVG elements can be programmatically manipulated using the SVG Document Object Model (DOM), which extends the standard DOM to provide interfaces specific to vector graphics. The SVG DOM allows JavaScript to dynamically create, modify, and interact with SVG content by treating it as a tree of nodes. Key methods includecreateElementNS, which creates an element in the SVG namespace (URI: http://www.w3.org/2000/svg), ensuring proper namespace handling to avoid rendering issues in browsers. For instance, to create a circle element, one would use document.createElementNS('http://www.w3.org/2000/svg', 'circle'). Once created, elements can be appended to the SVG document using appendChild, enabling runtime construction of complex graphics. This approach is defined in the SVG 2 specification, which builds on the core DOM for seamless integration with web pages.[1][99]
Event listeners enhance interactivity by attaching JavaScript functions to SVG elements for responding to user actions. Common attributes include onclick for click events and onmouseover for hover effects, which can be set directly on elements or via the addEventListener method for more flexibility. For example, an SVG rectangle might use addEventListener('click', function() { ... }) to trigger a color change. These events propagate through the DOM, allowing scripts to handle interactions like tooltips or selections on shapes and paths. The SVG specification supports all standard DOM events, with SVG-specific attributes listed in the event handling guidelines.[100]
JavaScript libraries simplify SVG manipulation by abstracting DOM complexities. D3.js (Data-Driven Documents) excels in data-driven SVG generation, using selections to bind data to elements and apply transitions for smooth updates, making it ideal for visualizations like charts. Snap.svg, developed by Adobe, provides a concise API for creating and animating SVG with methods like paper.circle() for instant element creation and animate() for transformations, supporting modern features such as gradients and clipping. Both libraries leverage the SVG DOM but offer higher-level abstractions for efficient development.[101][102]
A practical example of JavaScript-driven animation involves dynamically altering an SVG circle's radius in a loop. Consider the following code, which selects an existing <circle> element and increments its radius over time using requestAnimationFrame for smooth performance:
const circle = document.querySelector('circle');
let radius = 20;
function animate() {
circle.setAttribute('r', radius);
radius += 1;
if (radius < 100) {
requestAnimationFrame(animate);
}
}
animate();
const circle = document.querySelector('circle');
let radius = 20;
function animate() {
circle.setAttribute('r', radius);
radius += 1;
if (radius < 100) {
requestAnimationFrame(animate);
}
}
animate();
setAttribute, contrasting with declarative methods.
For performance optimization in scripted SVG, batching updates minimizes reflows and repaints, particularly in complex scenes. Using beginElement on SMIL animation elements from JavaScript can synchronize multiple changes, as it triggers predefined animations efficiently without repeated DOM queries. This method, part of the SVGAnimationElement interface, ensures updates occur in a single rendering cycle, reducing computational overhead in loops or data bindings.[103]
SMIL-Based Animation
SVG's native animation capabilities are based on the Synchronized Multimedia Integration Language (SMIL) Animation specification, which provides declarative syntax for defining time-based modifications to element attributes. The core elements include<animate>, which interpolates between values for scalar attributes like opacity or length; <animateMotion>, which moves an element along a specified path; and <animateTransform>, which applies transformations such as rotation, scaling, or translation to an element's transform attribute.[104] These elements are embedded within the target SVG element and support linear or paced interpolation to create smooth animations without requiring scripting.
Key attributes control the animation's behavior and timing. The from and to attributes set the starting and ending values, while dur specifies the duration (e.g., "3s" for three seconds). Repetition is handled by repeatCount, which can be a numeric value or "indefinite" for continuous looping. Timing is further refined with begin and end to define activation and termination points relative to the document timeline, and keyTimes provides a list of normalized time fractions (e.g., "0; 0.5; 1") paired with values for non-linear pacing during interpolation.[104] This declarative approach allows animations to run independently of user interactions, focusing on timeline-driven effects.
In SVG 2, SMIL-based animation has been removed from the specification, marking its deprecation in favor of more integrated web technologies.[105] Developers are recommended to migrate to CSS animations using @keyframes for stylistic changes or the Web Animations API for programmatic control, as these offer better performance and broader interoperability.[106] For complex scripted animations, JavaScript libraries can provide similar functionality with greater flexibility.
A simple example animates an element's opacity from transparent to fully visible over three seconds:
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
<circle cx="50" cy="50" r="40" fill="blue" opacity="0">
<animate attributeName="opacity" from="0" to="1" dur="3s" fill="freeze" />
</circle>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
<circle cx="50" cy="50" r="40" fill="blue" opacity="0">
<animate attributeName="opacity" from="0" to="1" dur="3s" fill="freeze" />
</circle>
</svg>
fill="freeze" attribute to retain the final state after completion.[104]
Browser support for SMIL animations remains robust in 2025, with full implementation in Firefox since version 4, Chrome since version 5, Edge since version 79, and Safari since version 6, though older Safari versions had partial support limited to non-HTML contexts.[107] Deprecation warnings may appear in Chrome's developer console, signaling the shift away from SMIL, but animations continue to function for compatibility.[106]
Event Handling and User Interaction
SVG supports user interaction through a rich set of event handling mechanisms integrated with the Document Object Model (DOM), allowing elements to respond to inputs such as mouse clicks, keyboard actions, and touch gestures.[108] Event handlers can be defined inline using attributes likeonpointerdown or attached dynamically via JavaScript, enabling reactive behaviors in graphical elements like paths and shapes.[109] This interactivity is essential for creating dynamic visualizations, such as interactive charts or maps, where user inputs trigger visual feedback or data updates.
Standard DOM events, as defined in the UI Events specification, are fully supported in SVG, including pointerdown for initiating pointer interactions, wheel for scrolling or zooming via mouse wheel, and focus for managing element selection.[110] These events follow the DOM event flow, propagating through the document tree to allow coordinated responses across nested SVG elements. SVG-specific events extend this model.[111] This event bubbles up the DOM hierarchy but cannot be canceled, providing developers with hooks to synchronize zoom states in applications.[112]
Pointer events form the core of mouse and touch-based interactions in SVG, governed by the pointer-events CSS property to control how elements receive input.[113] This property accepts values like visiblePainted (which considers both fill and stroke for hit detection), stroke (limited to stroke outlines), or none (disabling events entirely), enabling precise targeting for complex paths where hit-testing determines if a pointer intersects the element's geometry.[114] For example, in a detailed vector map, setting pointer-events: visibleStroke on path elements allows clicks to register only along boundaries, ignoring internal areas. Cursor styles enhance this by changing the pointer appearance—via the cursor property with values like pointer for clickable elements or crosshair for selection tools—providing visual cues during hover states.[115] Custom cursors can even reference external images through the <cursor> element, supporting URIs to PNG files for tailored interactivity.[116]
Accessibility in SVG event handling is bolstered by keyboard navigation features, aligning with web standards to ensure inclusive user experiences. The tabindex attribute can be applied to focusable elements like <svg>, <a>, or those with interactive attributes (e.g., controls), assigning a tab order for sequential navigation via the Tab key.[](https://www.w3.org/TR/SVG2/interact.html#A tabindexAttribute) Elements with tabindex="0" integrate into the natural document focus order, while positive values (e.g., tabindex="1") prioritize them explicitly, allowing keyboard users to activate events like focus or click without a mouse. Visual focus indicators, such as outlines, are rendered automatically, and developers can style them using CSS pseudo-classes like :focus.[117]
A key concept in SVG event processing is bubbling, where events propagate from the target element up through its ancestors in the DOM tree, enabling centralized handling in nested structures. For instance, a pointerdown event on a child <path> within a <g> group will first trigger the target's handler, then bubble to the group and potentially the root <svg>, unless stopped via event.stopPropagation().[112] This mechanism is crucial for complex diagrams, where parent elements might aggregate interactions from multiple children without duplicating code. SVG-specific events also participate in bubbling, ensuring consistent behavior across the document.[111]
SVG 2 introduces enhancements for mobile and touch-based interactions by fully integrating the Pointer Events API, which unifies mouse, touch, and pen inputs into a single model.[108] This provides better support for multi-touch gestures, such as pinch-to-zoom, through events like pointermove and pointerup, with improved hit-testing that accounts for touch pressure and coordinates. Unlike earlier versions reliant on separate touch event sets, SVG 2's approach reduces compatibility issues on devices, allowing seamless event handling across input types without platform-specific code.[118]
Implementation
Browser and Device Support
SVG enjoys widespread support across modern desktop browsers for the SVG 1.1 specification, with full implementation in Google Chrome starting from version 4, Mozilla Firefox from version 3, Apple Safari from version 3.2, and Microsoft Edge from version 12.[6] These browsers handle core features such as paths, shapes, text, and basic styling without significant issues in their latest versions as of 2025 (Chrome 142, Firefox 145, Safari 26.1, Edge 142). However, support for SVG 2 remains partial, though full compliance is not yet achieved across all vendors.[28] On mobile platforms, iOS Safari has provided full SVG 1.1 support since version 3.2, enabling seamless rendering on iPhones and iPads running iOS 13 and later.[6] Android browsers, including Chrome for Android, offer full support from Android 4.4 (KitKat) onward, covering the majority of devices in use today; however, older Android versions (pre-4.4) exhibit limitations such as incomplete masking and scaling.[119] Limitations persist on legacy mobile devices, particularly those with outdated firmware or non-standard browsers like older Opera Mini variants, where basic rendering may fail or degrade performance. Certain SVG features show incomplete or inconsistent support. For instance, SMIL-based animations were deprecated in Chrome in 2015 due to preferences for CSS and Web Animations API, though implementation remains available in Chrome versions 5 through 141; support has been removed in version 142 and later.[107] Filter effects, while broadly supported (full in Firefox 3+, Chrome 8+, Safari 6+, Edge 12+), exhibit variations in advanced capabilities like feDropShadow or certain blending modes across browsers.[120] To address gaps, particularly in older browsers like Internet Explorer 9-11 that partially support SVG but fail on external references via theAuthoring Tools and Software
SVG authoring tools encompass a range of software designed for creating, editing, and exporting Scalable Vector Graphics (SVG) files, catering to both graphical interface users and those preferring code-based workflows. These tools leverage SVG's XML-based structure to enable precise vector manipulation, ensuring scalability without loss of quality. Vector graphics editors provide intuitive graphical user interfaces (GUIs) for drawing paths, shapes, and text, while code editors facilitate direct XML editing for fine-tuned control. Online platforms offer browser-based accessibility, making SVG creation collaborative and device-agnostic.[122] Among dedicated vector editors, Inkscape stands out as a free, open-source application with native SVG support, allowing users to create complex illustrations using tools that directly correspond to SVG elements like the<path> command for Bézier curves and shapes. It includes features for object manipulation, text handling, and exporting optimized SVGs, making it suitable for professional and hobbyist workflows across Windows, macOS, and Linux.[123] Adobe Illustrator, a commercial vector editor from Adobe, supports SVG export through its File > Export menu, producing high-quality files with options for artboard-specific output and styling preservation, though it requires careful settings to avoid unnecessary bloat in the resulting XML.[124]
For code-based authoring, text editors like Visual Studio Code (VS Code) enable direct SVG editing via extensions that provide syntax highlighting, preview, minification, and prettification features, treating SVG as editable XML markup. Plugins such as the SVG extension integrate these capabilities, allowing developers to author SVGs inline with HTML or JavaScript while validating structure in real-time.[125][126]
Browser-based tools democratize SVG creation without installations. Figma, a collaborative design platform, facilitates vector icon and graphic design with plugins like SVG Toolkit for clean exports, ensuring minimal clutter in the output code for web use. SVG-Edit, an open-source JavaScript-driven editor, runs entirely in modern browsers, offering drawing tools for paths, rectangles, and text directly within the SVG canvas, ideal for quick edits or embedding in web applications.[127][128]
Export considerations are crucial to maintain SVG efficiency; tools often generate verbose code that can be optimized post-export using SVGO, a Node.js-based command-line utility that removes redundancies, collapses attributes, and reduces file size by up to 70% without visual loss, via plugins like cleanupAttrs and removeDoctype. This step is essential for web deployment, as unoptimized SVGs can impact loading times.[129][130]
Libraries and APIs
Several libraries and APIs enable programmatic generation and manipulation of SVG content across various programming languages, facilitating dynamic vector graphics in applications. These tools abstract the complexities of SVG's XML structure, allowing developers to create, modify, and render SVG elements through code rather than manual markup.[101][131][132] In JavaScript, D3.js (Data-Driven Documents) is a prominent library for building interactive data visualizations, particularly charts and graphs, by binding data to SVG elements such as paths and shapes. It leverages web standards to manipulate the Document Object Model (DOM), enabling scalable and responsive graphics that update based on data changes.[133] For canvas-like editing of SVG, Fabric.js provides an interactive object model on top of HTML5 canvas, supporting SVG import, export, and real-time manipulation of elements like groups and paths, making it suitable for applications requiring user-driven modifications.[131] Building on JavaScript DOM access for SVG, these libraries extend core scripting capabilities to handle complex visualizations efficiently.[134] For other languages, Python's svgwrite library offers a straightforward API to generate SVG files programmatically, supporting vector shapes, text, and styles without external dependencies, ideal for automated diagram creation. In Java, Apache Batik serves as a comprehensive toolkit for SVG rendering, generation, and manipulation, including a full SVG DOM implementation and utilities like SVGGraphics2D for converting Java 2D graphics to SVG output.[135][132] Web APIs, such as the SVG Document Object Model (DOM) extensions defined by the W3C, provide standardized interfaces for accessing and altering SVG elements within browsers, forming the foundation for higher-level libraries. On the server side, Node.js modules like SVG.js enable SVG creation and animation in a lightweight, dependency-free manner, often paired with adapters like svgdom for non-browser environments, supporting tasks such as batch generation of vector assets.[136] These libraries are commonly used to produce dynamic SVGs for interactive dashboards and automated reports, where data-driven updates ensure visualizations remain current without manual redesign; for instance, in business intelligence tools like Power BI, SVGs allow custom, scalable icons and gauges that respond to real-time metrics.[137] A key example is D3.js's data binding mechanism, which uses patterns like enter, update, and exit to dynamically generate and modify<path> elements based on datasets, such as plotting variable curves in a line chart where each path's d attribute is computed from data points.[101]
Advanced Topics
Compression Techniques
SVG files, being XML-based, lend themselves to text-based optimization techniques that reduce redundancy without altering the rendered output. These methods include removing unnecessary attributes, such as default values or metadata not required for display, and shortening path data by converting absolute coordinates to relative ones or eliminating redundant commands. For instance, the SVGO tool employs plugins likeremoveAttrs to strip extraneous attributes and convertPathData to optimize path commands, often achieving substantial size reductions in exported SVGs from design software.
Further refinements involve reducing the precision of numeric values, such as rounding decimal places in coordinates from six to three digits where visual fidelity remains intact, and removing duplicates like repeated definitions or identical elements. The cleanupNumericValues plugin in SVGO handles precision reduction, while removeDuplicates eliminates redundant items, contributing to cleaner, more compact files. Similarly, the Scour optimizer aggressively cleans SVG structure by optimizing paths and removing cruft, making it suitable for batch processing.[138]
For web serving, the standard approach is applying gzip compression to produce SVGz files, which the SVG specification recommends using the .svgz extension for. This deflate-based method typically yields compression ratios of 77% to 84% on uncompressed SVGs, depending on content complexity, as demonstrated in W3C benchmarks where files reduced from around 12-18 KB to 2-4 KB.[24][139]
These optimizations balance file size against maintainability, as aggressive minification can hinder future editing by obfuscating structure or shortening identifiers, though configurable presets in tools like SVGO allow users to toggle plugins for editable outputs. For line art, such as diagrams or icons, optimized SVGs can be up to several times smaller than equivalent PNG raster files, with examples showing compressed SVGs at 13.6 KB versus 56 KB PNGs, enhancing web performance for scalable graphics.[140][141]
Mobile and Embedded Profiles
To address the constraints of resource-limited environments such as early mobile phones and personal digital assistants (PDAs), the World Wide Web Consortium (W3C) developed specialized profiles of Scalable Vector Graphics (SVG). These profiles subset the full SVG specification to prioritize efficiency in processing power, memory, and rendering capabilities. The primary profiles are SVG Tiny and SVG Basic, both introduced as part of the Mobile SVG Profiles in 2003.[23] SVG Tiny 1.2, formalized as a W3C Recommendation in December 2008, targets low-end devices like cellphones and basic PDAs. It supports core vector graphics elements including basic shapes (such as rectangles, circles, and paths), text, raster image inclusion, and simple animations via SMIL (Synchronized Multimedia Integration Language). While it includes limited scripting through ECMAScript and a micro DOM (uDOM) for basic interactivity, complex features like advanced filters, clipping paths, and full CSS styling are excluded to minimize computational overhead. This profile emphasizes lightweight file sizes and fast rendering, making it suitable for environments with limited bandwidth and battery resources.[142] In contrast, SVG Basic serves mid-range devices such as higher-end PDAs and early smartphones, offering a broader subset of SVG 1.1 features. It includes support for gradients, more extensive text handling, and basic scripting, but still omits demanding elements like complex animations and foreign object embedding to balance performance and functionality. Both profiles facilitate scalable graphics without quality loss, enabling applications like maps and icons on small screens.[23] Beyond traditional mobile use, SVG profiles find application in embedded systems, where they are integrated into formats like PDFs and EPUBs for digital publishing. In PDFs, SVG content can be embedded as vector objects, preserving scalability when viewed in compatible readers, though conversion to PDF-native paths is often required for full interoperability. EPUB 3.3 explicitly supports SVG for illustrations and layouts in electronic books, allowing vector-based reflowable or fixed-layout content that adapts to various e-readers. In mobile applications, SVG is incorporated via WebView components on Android and iOS platforms; Android's VectorDrawable API directly imports simplified SVG paths for native rendering, while iOS 13 and later provides built-in SVG support, enabling responsive designs with CSS media queries to adjust graphics based on screen size or orientation.[143] As of 2025, full SVG 1.1 is widely viable on modern smartphones and tablets, with near-universal browser support across iOS Safari, Android Chrome, and other engines, rendering the Tiny and Basic profiles largely legacy for consumer mobiles. However, these subsets remain relevant for Internet of Things (IoT) and deeply embedded systems, such as microcontrollers and industrial displays, where libraries like SEGGER emWin and ThorVG provide optimized SVG rendering with minimal footprint. To enhance performance in these contexts, developers reduce DOM depth by limiting nested elements, avoid resource-intensive filters and gradients, and simplify paths—strategies that conserve battery life by lowering CPU usage during rendering and animation. For instance, in responsive mobile apps, media queries allow SVG elements to scale efficiently without excessive redraws, ensuring smooth operation on battery-powered devices.[6][144][145]Printing and Export Options
SVG's vector-based nature ensures resolution-independent output, making it well-suited for high-quality printing without pixelation at various scales. Tools like Inkscape enable direct rendering of SVG files to PDF format, preserving vector paths, text, and shapes for professional print workflows.[146] This process maintains scalability, allowing designers to output documents at any resolution while leveraging SVG's precise geometric definitions.[1] For professional printing, SVG files can be exported to Encapsulated PostScript (EPS) or PostScript (PS) formats using authoring tools such as Inkscape, which convert vector elements into printer-compatible streams.[146] These formats are ideal for desktop publishing and offset printing, where PostScript's device-independent model aligns with SVG's parametric descriptions. In cases requiring raster integration, such as legacy systems, SVG can be exported to PNG as a fallback, though this sacrifices vector advantages for bitmap compatibility.[146] Color management in SVG supports International Color Consortium (ICC) profiles, enabling accurate color reproduction across devices by embedding profile data within the file.[147] SVG 2 drafts introduce support for CMYK colors through unmanaged device-cmyk specifications, allowing direct targeting of print devices alongside RGB fallbacks for broader compatibility.[147] This facilitates workflows in print production, where CMYK is standard for four-color processes. Printing complex SVG graphics presents challenges, particularly with filters like blurs or shadows, which often require rasterization to bitmap intermediates during export or rendering to ensure compatibility with print drivers.[148] In tools like Inkscape, such effects are rasterized at a specified DPI (default 96, adjustable up to 400 for printing), potentially increasing file size and complicating edits, though options exist to ignore filters for pure vector output.[146] Designers must test outputs for issues like bleed and trim marks, verifying alignment in the final PDF or PS to meet print specifications.[146] The<foreignObject> element extends SVG's utility in print layouts by embedding HTML or other non-SVG content, such as formatted text blocks, within vector regions for hybrid designs.[149] This allows integration of complex typography or tables into printable SVG documents, rendered via the user agent's HTML engine while maintaining overall vector integrity.[149]
Security Considerations
Common Vulnerabilities
Scalable Vector Graphics (SVG) files, being XML-based, are susceptible to XML External Entity (XXE) attacks when parsers process external entity declarations without proper restrictions. Attackers can embed malicious entity references in SVG documents to disclose sensitive files on the server or perform server-side request forgery by tricking the parser into fetching remote resources. For instance, libraries handling SVG input, such as certain .NET packages, have been found vulnerable to XXE due to inadequate disabling of external entity loading, potentially leading to data exfiltration during file processing.[150][151] Another significant risk involves script injection through embedded JavaScript in SVG elements, particularly when files are rendered without sanitization in web contexts. Malicious actors can include<script> tags or event handlers like onload within SVG to execute arbitrary code, enabling cross-site scripting (XSS) attacks that compromise user sessions or steal credentials. This vulnerability is exacerbated in scenarios like user-uploaded profile images, where unsanitized SVGs are displayed directly in HTML, allowing the injected scripts to run in the victim's browser context.[152][153]
Resource exhaustion attacks can occur due to deeply nested structures or recursive references in SVG elements, such as excessive nesting in <g> groups or infinite loops via the <use> element, which may cause stack overflows during rendering. Browsers and parsers attempting to resolve these constructs can consume excessive memory or CPU, leading to denial-of-service (DoS) conditions. In 2025, a notable issue in Chromium-based browsers involved uncontrolled recursion when parsing data URIs embedded in SVG attributes, resulting in stack exhaustion; this was addressed in patches released in late October to mitigate potential crashes from specially crafted files.[154]
SVG's support for hyperlinks via <a> elements introduces phishing risks, as attackers can embed deceptive links that redirect users to malicious sites while masquerading as legitimate graphics. These hyperlinks can be obscured within interactive SVG content, such as clickable maps or icons, tricking users into divulging credentials or downloading malware upon interaction. Phishing campaigns in 2025 have increasingly exploited this by distributing SVG attachments in emails that appear benign but contain hidden <a> redirects to fraudulent domains, bypassing traditional email filters.[155][156]
Mitigation Strategies
To mitigate security risks associated with SVG, particularly those involving script execution and resource loading, developers should employ client-side sanitization libraries such as DOMPurify, which removes malicious elements like scripts and external references from SVG content before rendering it in the DOM.[157] This approach is especially effective for user-uploaded SVGs, as it parses and strips unsafe attributes and tags while preserving valid vector graphics.[158] Server-side enforcement of Content-Security-Policy (CSP) headers provides an additional layer of protection by blocking inline JavaScript execution within SVGs, using directives likescript-src 'self' to restrict sources and unsafe-inline avoidance. For instance, a policy such as img-src 'self' data:; object-src 'none'; prevents unauthorized script loading from SVG elements.[159]
During SVG upload processes, rigorous validation against the official SVG schema ensures structural integrity and compliance, using tools like XML parsers with the W3C SVG 1.1 DTD to reject malformed or oversized files.[160] Additionally, limiting element nesting depth—such as capping layer nesting at 50 levels in rendering engines like librsvg—prevents stack exhaustion from deeply recursive structures that could exploit processing limits.[161]
Adopting best practices further reduces exposure: prefer embedding SVGs inline within HTML for finer control over styling and sanitization, rather than loading external files that may evade checks.[152] Avoid using the <foreignObject> element with untrusted HTML content, as it can introduce executable code outside the SVG namespace.[152]
In high-risk environments, such as enterprise browsers or email clients, configure settings to disable SVG rendering entirely; for example, Microsoft Outlook has implemented policies to block inline SVG display to counter phishing vectors.[162]
