W3C

Scalable Vector Graphics (SVG) 2

W3C Candidate Recommendation 15 September 2016

This version:
https://www.w3.org/TR/2016/CR-SVG2-20160915/
Latest version:
https://www.w3.org/TR/SVG2/
Latest editor's draft:
https://svgwg.org/svg2-draft/
Previous version:
https://www.w3.org/TR/2015/WD-SVG2-20150915/
Single page version:
https://www.w3.org/TR/2016/CR-SVG2-20160915/single-page.html
GitHub repository:
https://github.com/w3c/svgwg/
Public comments:
www-svg@w3.org (archive)
Editors:
Nikos Andronikos, Canon, Inc. <nikos.andronikos@cisra.canon.com.au>
Rossen Atanassov, Microsoft Co. <ratan@microsoft.com>
Tavmjong Bah, Invited Expert <tavmjong@free.fr>
Amelia Bellamy-Royds, Invited Expert <amelia.bellamy.royds@gmail.com>
Brian Birtles, Mozilla Japan <bbirtles@mozilla.com>
Bogdan Brinza, Microsoft Co. <bbrinza@microsoft.com>
Cyril Concolato, Telecom ParisTech <cyril.concolato@telecom-paristech.fr>
Erik Dahlström, Invited Expert <erik@dahlström.net>
Chris Lilley, W3C <chris@w3.org>
Cameron McCormack, Mozilla Corporation <cam@mcc.id.au>
Doug Schepers, W3C <schepers@w3.org>
Dirk Schulze, Adobe Systems <dschulze@adobe.com>
Richard Schwerdtfeger, IBM <schwer@us.ibm.com>
Satoru Takagi, KDDI Corporation <sa-takagi@kddi.com>
Jonathan Watt, Mozilla Corporation <jwatt@jwatt.org>

Abstract

This specification defines the features and syntax for Scalable Vector Graphics (SVG) Version 2. SVG is a language based on XML for describing two-dimensional vector and mixed vector/raster graphics. SVG content is stylable, scalable to different display resolutions, and can be viewed stand-alone, mixed with HTML content, or embedded using XML namespaces within other XML languages. SVG also supports dynamic changes; script can be used to create interactive documents, and animations can be performed using declarative animation features or by using script.

Status of This Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.

This document is the 15 September 2016 Candidate Recommendation of SVG 2. This version of SVG builds upon SVG 1.1 Second Edition by improving the usability of the language and by adding new features commonly requested by authors. The Changes appendix lists all of the changes that have been made since SVG 1.1 Second Edition.

Comments on this Candidate Recommendation are welcome. Comments can be sent to www-svg@w3.org, the public email list for issues related to vector graphics on the Web. This list is archived and senders must agree to have their message publicly archived from their first posting. To subscribe send an email to www-svg-request@w3.org with the word subscribe in the subject line.

The specification includes a number of annotations that the Working Group is using to record links to meeting minutes and resolutions where specific decisions about SVG features have been made. Different coloring is also used to mark the maturity of different sections of the specification:

In this Candidate Recommendation, by default, the background colors indicating section maturity are hidden and only annotations that record specific requirements for SVG 2 as part of our requirements gathering exercise are visible. To view the section maturity background colors and any additional annotations, the "All annotations" alternate style sheet can be used.

This document has been produced by the W3C SVG Working Group as part of the Graphics Activity within the W3C Interaction Domain. The goals of the W3C SVG Working Group are discussed in the W3C SVG Charter. The W3C SVG Working Group maintains a public Web page, https://www.w3.org/Graphics/SVG/, that contains further background information. The authors of this document are the SVG Working Group participants.

The entrance criteria for this document to move to Proposed Recommendation with at least two independent implementations passing each new feature. The Working Group will prepare an implementation report to track progress.

W3C publishes a Candidate Recommendation to indicate that the document is believed to be stable and to encourage implementation by the developer community. This Candidate Recommendation is expected to advance to Proposed Recommendation no earlier than 10 November 2016.

Publication as a Candidate Recommendation does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

A list of current W3C Recommendations and other technical documents can be found at https://www.w3.org/TR/. W3C publications may be updated, replaced, or obsoleted by other documents at any time.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document is governed by the 1 September 2015 W3C Process Document.

All features in this specification depend upon implementation in browsers or authoring tools. If a feature is not certain to be implemented, we define that feature as "at risk". At-risk features will be removed from the current specification, and may be included in future versions of the specification. If an at-risk feature is particularly important to authors of SVG, those authors are encouraged to give feedback to implementers regarding its priority. The following features are at risk, and may be dropped during the CR period:

Acknowledgments

The SVG Working Group would like to thank the following people for contributing to this specification with patches or by participating in discussions that resulted in changes to the document: David Dailey, Eric Eastwood, Jarek Foksa, Daniel Holbert, Paul LeBeau, Robert Longson, Henri Manson, Ms2ger, Kari Pihkala, Philip Rogers, David Zbarsky.

In addition, the SVG Working Group would like to acknowledge the contributions of the editors and authors of the previous versions of SVG – as much of the text in this document derives from these earlier specifications – including:

Finally, the SVG Working Group would like to acknowledge the great many people outside of the SVG Working Group who help with the process of developing the SVG specifications. These people are too numerous to list individually. They include but are not limited to the early implementers of the SVG 1.0 and 1.1 languages (including viewers, authoring tools, and server-side transcoders), developers of SVG content, people who have contributed on the www-svg@w3.org and svg-developers@yahoogroups.com email lists, other Working Groups at the W3C, and the W3C Team. SVG 1.1 is truly a cooperative effort between the SVG Working Group, the rest of the W3C, and the public and benefits greatly from the pioneering work of early implementers and content developers, feedback from the public, and help from the W3C team.


Chapter 1: Introduction

1.1. About SVG

This specification defines the features and syntax for Scalable Vector Graphics (SVG).

SVG is a language for describing two-dimensional graphics. As a standalone format or when mixed with other XML, it uses the XML syntax [xml]. SVG code used inside HTML documents uses the HTML syntax [HTML]. SVG allows for three types of graphic objects: vector graphic shapes (e.g., paths consisting of straight lines and curves), images and text. Graphical objects can be grouped, styled, transformed and composited. The feature set includes nested transformations, clipping paths, alpha masks, filter effects and template objects.

SVG drawings can be interactive and dynamic. Animations can be defined and triggered either declaratively (i.e., by embedding SVG animation elements in SVG content) or via scripting.

Sophisticated applications of SVG are possible by use of a supplemental scripting language which accesses SVG Document Object Model (DOM), which provides complete access to all elements, attributes and properties. A rich set of event handlers can be assigned to any SVG graphical object. Within a web page, the same scripts can work on both HTML and SVG elements. Scripting.

SVG is useful for rich graphical presentation of information, including a number of accessibility features that, used correctly, ensure the content can be used by the widest possible audience. But a direct link to source data, where possible, is helpful for many people to understand the content provided.

1.2. Compatibility with other standards efforts

SVG leverages and integrates with other W3C specifications and standards efforts, as described in the following:

1.3. Normative Terminology

Within this specification, the key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" are to be interpreted as described in Key words for use in RFCs to Indicate Requirement Levels [rfc2119]. However, for readability, these words do not appear in all uppercase letters in this specification.

At times, this specification recommends good practice for authors and user agents.


Chapter 2: Conformance Criteria

2.1. Overview

Graphics defined with SVG have many different applications. As a result, not all software that uses SVG will have the same features. Conformance to the SVG specification is therefore not a binary matter; sofware may be conforming within a restricted feature set.

Furthermore, SVG is designed to be integrated into other types of documents; depending on the type of integration, only a limited feature-set may be appropriate. There are various ways that an SVG document fragment can be referenced by or included in other documents and thereby be processed by a user agent. SVG documents can also be viewed directly, as the primary document. Each different method by which an SVG document fragment can be used implies a certain set of requirements on how the SVG document fragment must be processed.

This chapter therefore defines a number of processing modes that encompass the different combinations of features which may be enabled or disabled in the document. In addition, it specifies normative requirements for which processing mode must be used when SVG documents reference or embed other SVG documents. The same set of processing modes may be used by reference in other specifications to describe how SVG documents should be processed.

This document does not place normative requirements on other specifications that can reference or include SVG documents, such as HTML and various CSS specifications. The intention is for these other specifications to normatively point to the appropriate processing mode from this document.

This chapter also outlines specific conformance requirements for different types of SVG content, and different classes of software that use or create SVG.

2.2. Processing modes

This section defines a standard set of processing modes for SVG documents. Each processing mode specifies whether certain high level SVG features are enabled.

2.2.1. Features

The features that can be enabled or disabled depending on the processing mode are as follows:

declarative animation

Declarative animation includes both the animation elements in SVG – animate, animateMotion, animateTransform and set – and CSS Transitions and Animations (see the Animation appendix for details). When declarative animations are disabled in an SVG document, any animation elements or CSS Transitions or Animations must not be applied or run.

This is not the same as pausing the document's animated state at 0s document time; if an animation is defined to begin at 0s, it still will not be applied.

references to external resources

References to external resources are URLs references or network access requests made by markup, style properties, script or other Web platform features used in the document, except for:

When external references are disabled in an SVG document, any attempt to fetch a document through an external reference must instead be treated as if a network error occurred and no data was received.

When external references are enabled, user agents that support external file requests from the Internet must adhere to the restrictions on cross-origin resource fetching, as outlined in the Linking chapter.

script execution

Script execution is the execution of any SVG script elements, script found in event attributes (such as onclick on SVG elements), or any other script defined by other Web platform features used in the document, such as any HTML script elements. When script execution is disabled in an SVG document, no script in the document must be run.

interaction

Interaction refers to the delivery of DOM Events or the invocation of any user agent specific UI behaviors such as text selection, focus changing, link traversal, or animation or transition triggering that is done in response to user input such as mouse or keyboard activity. When interaction is disabled in an SVG document, any user input events that would be targetted at the document or any elements within the document must have no effect.

2.2.2. Dynamic interactive mode

This processing mode imposes no restrictions on any feature of the SVG language.

Dynamic Interactive Features
script execution yes
external references yes
declarative animation yes
interactivity yes

2.2.3. Animated mode

This processing mode is intended for circumstances where an SVG document is to be used as an animated image that is allowed to resolve external references, but which is not intended to be used as an interactive document.

Animated Features
script execution no
external references yes
declarative animation yes
interactivity no

2.2.4. Secure animated mode

This processing mode is intended for circumstances where an SVG document is to be used as an animated image that is not allowed to resolve external references, and which is not intended to be used as an interactive document. This mode might be used where image support has traditionally been limited to raster images (such as JPEG, PNG and GIF).

Secure Animated Features
script execution no
external references no
declarative animation yes
interactivity no

2.2.5. Static mode

This processing mode is intended for circumstances where an SVG document is to be used as a non-animated image that is allowed to resolve external references, but which is not intended to be used as an interactive document. For example, an SVG viewer that processes graphics for inclusion in print documents would likely use static mode.

Static Features
script execution no
external references yes
declarative animation no
interactivity no

2.2.6. Secure static mode

This processing mode is intended for circumstances where an SVG document is to be used as a non-animated image that is not allowed to resolve external references, and which is not intended to be used as an interactive document. This mode might be used where image support has traditionally been limited to non-animated raster images (such as JPEG and PNG.)

Secure Static Features
script execution no
external references no
declarative animation no
interactivity no

2.3. Processing modes for SVG sub-resource documents

When an SVG document is viewed directly, it is expected to be displayed using the most comprehensive processing mode supported by the user agent. However, when an SVG is processed as a sub-resource or embedded document, the following restrictions must apply:

image references

An SVG embedded within an image element must be processed in secure animated mode if the embedding document supports declarative animation, or in secure static mode otherwise.

The same processing modes are expected to be used for other cases where SVG is used in place of a raster image, such as an HTML ‘img’ element or in any CSS property that takes an <image> data type. This is consistent with HTML's requirement that image sources must reference "a non-interactive, optionally animated, image resource that is neither paged nor scripted" [HTML]

iframe references

SVG documents referenced by the an HTML iframe element in an SVG document must use the same processing mode as the embedding document, subject to any restrictions defined by the sandbox attribute on the embedding iframe.

The same processing rules are intended to be used when an SVG document is loaded in an HTML ‘embed’, ‘iframe’ or ‘object’ element [HTML]. An HTML document that is a top-level browsing context in an interactive web browser is equivalent to SVG's dynamic interactive processing mode.

use element and other href references

When SVG documents are loaded through use element references or paint server element cross-references they must be processed in secure static mode.

Note that animations do not run while processing the sub-resource document, for both performance reasons and because there is currently no context defined for resource documents to reference their timeline against. However, when elements from a sub-resource document are cloned into the current document because of a use element reference or paint-server cross-reference, the cloned element instances may be animated in the current document's timeline, as described in Animations in use-element shadow trees, and may trigger the loading of additional sub-resource files.

Graphical effects references

When SVG documents are loaded through any style property references that target specific elements in the document (as opposed to SVG as an image format), they must be processed in secure static mode.

Note that animations do not run in sub-resource documents, for both performance reasons and because there is currently no context defined for resource documents to reference their timeline against.

Some style properties may reference either specific elements or entire image files; the processing mode is more restrictive in the first case. For example, a reference to an SVG mask element will not be animated, but an entire SVG file used as an image mask can be.

SVG in fonts

When SVG files are processed as part of a font reference, they must use the secure animated mode if animated glyphs are supported, or secure static mode otherwise.

These restrictions are included in the OpenType specification for processing documents from the "SVG" table. OpenType also applies additional restrictions, in the form of a user agent style sheet that prevents rendering of text and foreign objects [OPENTYPE].

SVG document fragments that are included inline in a host document must use a processing mode that matches that of the host document. SVG document fragments included as children of an SVG foreignObject element must use the processing mode of the surrounding SVG document; non-SVG foreign content must be processed with equivalent restrictions.

For example, if an SVG document is being used in secure animated mode due to being referenced by an HTML ‘img’ or SVG image element, then any content within a foreignObject element must have scripts, interactivity, and external file references disabled, but should have declarative animation enabled.

2.3.1. Examples

Below are various methods of embedding SVG in an HTML page by reference, along with the expected processing mode and allowed features for each.

Each cell in the "Live Example" row should display a yellow smiley face. In each example below, clicking on the eyes tests link traversal, and clicking on the face tests declarative interactivity and script execution. The link should replace the image with a blue square (clicking on that will return you to the original image). The declarative interactivity uses the set element to change the face from shades of yellow to shades of green, and uses CSS pseudoclasses to add a stroke to the interactive elements. The script should fill in the smile. Time-based (as opposed to interactivity-based) declarative animation is supported if the left eye is winking (using the animate element) and if the eyes are dark blue with regular flashes of light blue (using CSS keyframe animation).

The expected processing modes and features outlined here are subject to any future changes in the corresponding HTML or CSS specification.

Embedding method object without sandboxing iframe with sandbox="" img CSS background
Expected processing mode dynamic interactive dynamic interactive, with restrictions secure animated secure animated
Declarative, time-based animation
(winking left eye, color-change in both eyes)
allowed allowed allowed allowed
Declarative, interactive animation and style changes
(face color changes when clicked, face/eyes outlined when hovered or focused)
allowed allowed disabled disabled
Link navigation within the same browsing context, to the same domain
(image changes when clicking eyes)
allowed allowed disabled disabled
Scripted interaction
(smile widens when clicking face)
allowed disabled (because of sandboxing) disabled disabled
Live example Your browser does not support embedded SVG images. smiley face, as an image
 

2.4. Document Conformance Classes

SVG is defined in terms of a document object model (DOM), rather than a particular file format or document type. For SVG content, therefore, conformance with this specification is defined by whether the content is or can generate a conforming DOM. Additional conformance classes depend on whether the content is also valid and well-formed XML [xml].

2.4.1. Conforming SVG DOM Subtrees

A DOM node tree or subtree rooted at a given element is a conforming SVG DOM subtree if it forms a SVG document fragment that adheres to the specification described in this document (Scalable Vector Graphics (SVG) Specification). Specifically, it:

SVG document fragments can be included within parent XML documents using the XML namespace facilities described in Namespaces in XML [xml-names]. Note, however, that since a conforming SVG DOM subtree must have an svg element as its root, the use of an individual non-svg element from the SVG namespace is disallowed. Thus, the SVG part of the following document is not conforming:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE SomeParentXMLGrammar PUBLIC "-//SomeParent" "http://SomeParentXMLGrammar.dtd">
<ParentXML>
  <!-- Elements from ParentXML go here -->
  <!-- The following is not conforming -->
  <z:rect xmlns:z="http://www.w3.org/2000/svg"
          x="0" y="0" width="10" height="10" />
  <!-- More elements from ParentXML go here -->
</ParentXML>

Instead, for the SVG part to become a conforming SVG DOM subtree, the file could be modified as follows:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE SomeParentXMLGrammar PUBLIC "-//SomeParent" "http://SomeParentXMLGrammar.dtd">
<ParentXML>
  <!-- Elements from ParentXML go here -->
  <!-- The following is conforming -->
  <z:svg xmlns:z="http://www.w3.org/2000/svg"
         width="100px" height="100px">
    <z:rect x="0" y="0" width="10" height="10"/>
  </z:svg>
  <!-- More elements from ParentXML go here -->
</ParentXML>

The SVG language and these conformance criteria provide no designated size limits on any aspect of SVG content. There are no maximum values on the number of elements, the amount of character data, or the number of characters in attribute values.

2.4.2. Conforming SVG Markup Fragments

A document or part of a document is a conforming SVG markup fragment if it can be parsed without error (other than network errors) by the appropriate parser for the document MIME type to form a conforming SVG DOM subtree, and in addition if:

2.4.3. Conforming XML-Compatible SVG Markup Fragments

A conforming SVG markup fragment is also a conforming XML-compatible SVG markup fragment if it:

2.4.4. Conforming XML-Compatible SVG DOM Subtrees

A DOM node tree or subtree rooted at a given element is an conforming XML-compatible SVG DOM subtree if, once serialized to XML, it could form a conforming XML-compatible SVG markup fragment.

If the DOM subtree cannot be serialized to conforming XML without altering it, such as when an id value is not a valid XML name, or when a Comment node's data contains the substring "--", then the subtree is not a conforming XML-compatible SVG DOM subtree.

2.4.5. Conforming SVG Stand-Alone Files

A document is a conforming SVG stand-alone file if:

2.5. Software Conformance Classes

For software, the requirements for conformance depend on the category of program:

SVG generators
Any software that creates or makes available SVG content, either as markup or as a DOM (as is the case with client-side JavaScript libraries).
SVG authoring tools
Any software that provides an interface for human content creators to manipulate graphics or code that will be used to generate SVG. SVG authoring tools are implicitly also SVG generators.
SVG servers
Any network or file server that makes available SVG content in response to requests from other software. SVG servers are implicitly also SVG generators.
SVG interpreters
Any software that parses or processes SVG documents or markup fragments. An SVG interpreter is an SVG user agent for the purpose of any sections of this specification that relate to the parsing or processing steps undertaken by the interpreter.
SVG viewers
Any software that creates a rendered graphical representation after parsing or processing an SVG document or SVG markup fragment. SVG viewers are implicitly also SVG interpreters. An SVG viewer is always an SVG user agent for the purpose of this specification.
SVG user agent
An SVG user agent is a user agent that is able to retrieve and render SVG content.
user agent

The general definition of a user agent is an application that retrieves and renders Web content, including text, graphics, sounds, video, images, and other content types. A user agent may require additional user agents that handle some types of content. For instance, a browser may run a separate program or plug-in to render sound or video. User agents include graphical desktop browsers, multimedia players, text browsers, voice browsers, and assistive technologies such as screen readers, screen magnifiers, speech synthesizers, onscreen keyboards, and voice input software.

In general terms, a "user agent" may or may not have the ability to retrieve and render SVG content; however, unless the context requires an alternative interpretation, all references to a "user agent" in this specification are assumed to be references to an SVG user agent that retrieves and renders SVG content.

Many programs will fall under multiple software classes. For example, a graphical editor that can import and display SVG files, allow the user to modify them, and then export the modified graphic to file, is an SVG interpreter, an SVG viewer, an SVG authoring tool, and an SVG generator.

2.5.1. Conforming SVG Generators

A conforming SVG generator is a SVG generator that:

SVG generators are strongly encouraged to use a Unicode character encoding by default, and to follow the other guidelines of the Character Model for the World Wide Web [UNICODE] [charmod].

SVG generators handling high-precision data are encouraged to follow the guidelines in the section Notes on generating high-precision geometry.

2.5.2. Conforming SVG Authoring Tools

An authoring tool, as defined in the Authoring Tool Accessibility Guidelines 2.0, is a conforming SVG authoring tool if it is a conforming SVG generator and it also conforms to all relevant Level A requirements from that document [atag20]. Level AA and Level AAA requirements are encouraged but not required for conformance.

2.5.3. Conforming SVG Servers

A conforming SVG server must meet all the requirements of a conforming SVG generator. In addition, conforming SVG servers using HTTP or other protocols that use Internet Media types must serve SVG stand-alone files with the media type "image/svg+xml".

Also, if the SVG file is compressed with gzip or deflate, conforming SVG Servers must indicate this with the appropriate header, according to what the protocol supports. Specifically, for content compressed by the server immediately prior to transfer, the server must use the "Transfer-Encoding: gzip" or "Transfer-Encoding: deflate" headers as appropriate, and for content stored in a compressed format on the server (e.g. with the file extension "svgz"), the server must use the "Content-Encoding: gzip" or "Content-Encoding: deflate" headers as appropriate.

Compression of stored content (the "entity," in HTTP terms) is distinct from automatic compression of the message body, as defined in HTTP/1.1 TE/ Transfer Encoding ([rfc2616], sections 14.39 and 14.41).

2.5.4. Conforming SVG Interpreters

An SVG interpreter is a program which can parse and process SVG document fragments. Examples of SVG interpreters are server-side transcoding tools or optimizers (e.g., a tool which converts SVG content into modified SVG content) or analysis tools (e.g., a tool which extracts the text content from SVG content, or a validity checker). A transcoder from SVG into another graphics representation, such as an SVG-to-raster transcoder, represents a viewer, and thus viewer conformance criteria also apply.

A conforming SVG interpreter must be able to parse and process all XML constructs defined in XML 1.0 [xml] and Namespaces in XML [xml-names].

A conforming SVG interpreter must parse any conforming XML-compatible SVG markup fragment in a manner that correctly respects the DOM structure (elements, attributes, text content, comments, etc.) of the content. The interpreter is not required to interpret the semantics of all features correctly.

If the SVG interpreter supports non-XML syntaxes (such as HTML), it must correctly parse any conforming SVG markup fragment in that syntax.

If the SVG interpreter runs scripts or fetches external resource files as a consequence of processing the SVG content, it must follow the restrictions described for user agents in Processing modes for SVG sub-resource documents and in the Linking chapter.

2.5.5. Conforming SVG Viewers

Action: Look at the performance class requirements and decide whether to remove points or move them into general requirements. (heycam)
Spec that calculation of CTMs should use double precision. (stakagi)
Resolution: Remove performance class requirements from SVG 2. ( ConformingHighQualitySVGViewers )
Purpose: To modulate the tradeoff of a numerical precision in use cases of the technical drawing and mapping, and the performance of user agent.
Owner: heycam, stakagi

An SVG viewer is a program which can parse and process an SVG document fragment and render the contents of the document onto some sort of graphical output medium such as a display, printer, or engraver. Thus, an SVG viewer is also an SVG interpreter (in that it can parse and process SVG document fragments), but with the additional requirement of correct rendering.

A conforming SVG viewer must be a conforming SVG interpreter, and must be able to support rendering output in at least one of the processing modes defined in this chapter:

A conforming SVG viewer must meet all normative requirements indicated in this specification for user agents, for all features supported by its processing mode(s).

Specific criteria that must apply to all conforming SVG viewers:

A conforming SVG viewer that supports processing modes that include interaction must support the following additional features:

A conforming SVG viewer that supports processing modes that include script execution must support the following additional features:

If the user agent includes an HTML or XHTML viewing capability or can apply CSS/XSL styling properties to XML documents, then a conforming SVG viewer must support resources of MIME type "image/svg+xml" wherever raster image external resources can be used, such as in the HTML or XHTML ‘img’ element and in CSS/XSL properties that can refer to raster image resources (e.g., ‘background-image’).

2.5.6. Conforming High-Quality SVG Viewer

In order for a conforming SVG viewer to be considered a conforming high-quality SVG viewer, it must support the following additional features:

A conforming high-quality SVG viewer that supports processing modes that include script execution, declarative animation, or interaction must support the following additional features:

A conforming high-quality SVG viewer that supports processing modes that include interaction must support the following additional features:


Chapter 3: Rendering Model

SVG 2 Requirement: Support the z-index.

Resolution: We will add Jonathan Watt's z-index proposal to SVG 2.

Auckland 2011 F2F day 5.

Purpose: Allow reordering (such as when a planet orbits the sun). Reordering without script support (e.g. CSS :hover).

Owner: Jonathan (Action 3002).

Status: Done.

The SVG 2 rendering model will follow the rules defined by the Compositing and Blending specification.

Resolution: Seattle/Paris 2012 F2F day 3.

Owner: Nikos (Action 3332).

Status: Done.

3.1. Introduction

Implementations of SVG must implement the rendering model as described in this chapter, as modified in the appendix on conformance requirementswhich describes situations where an implementation may deviate. In practice variability is allowed based on limitations of the output device (e.g. only a limited range of colors might be supported) and because of practical limitations in implementing a precise mathematical model (e.g. for realistic performance curves are approximated by straight lines, the approximation need only be sufficiently precise to match the conformance requirements).

The appendix on conformance requirements describes the extent to which an actual implementation may deviate from this description. In practice an actual implementation may deviate slightly because of limitations of the output device (e.g. only a limited range of colors might be supported) and because of practical limitations in implementing a precise mathematical model (e.g. for realistic performance curves are approximated by straight lines, the approximation need only be sufficiently precise to match the conformance requirements).

3.2. The rendering tree

The components of the final rendered representation of an SVG document do not have a one-to-one relationship with the underlying elements in the document model. The appearance of the graphic instead reflects a parallel structure, the rendering tree, in which some elements are excluded and others are repeated.

Many elements in the SVG namespace do not directly represent a component of the graphical document. Instead, they define graphical effects, metadata, content to be used to represent other elements, or alternatives to be displayed under certain conditions. In dynamic documents, certain components of the graphic may be rendered or not, depending on interaction or animation. These non-rendered elements are not directly included in the rendering tree.

Because SVG supports the reuse of graphical sub-components, some elements are rendered multiple times. The individual renderings may have context-dependent styling and may be rasterized at different scales or transformations.

3.2.1. Definitions

rendering tree

The rendering tree is the set of elements being rendered in an SVG document fragment. It is generated from the document tree by excluding non-rendered elements and inserting additional fragments for re-used graphics. Graphics are painted and composited in rendering-tree order, subject to stacking and re-ordering based on the z-index and paint-order properties. Note that elements that have no visual paint may still be in the rendering tree.

rendered element

An element that has a direct representation in the rendering tree for the current document. Includes a rendered instance of an element in a use-element shadow tree. Does not include elements that affect rendering as the source definition of re-used graphics but are not directly rendered themselves. See Rendered versus non-rendered elements

non-rendered element

An element that does not have a direct representation in the rendering tree for the current document. It may nonetheless affect the rendering tree as re-used graphics or graphical effects. See Rendered versus non-rendered elements.

re-used graphics

Graphical components that are included in the rendering tree but do not have a single direct equivalent element in the document model. They may be represented through shadow DOM elements (as in graphics re-used with a use element), or as image fragments generated as part of a graphical effect (as in patterns or masks).

never-rendered element

Any element type that is never directly rendered, regardless of context or display style value. It includes the following elements: clipPath, defs, desc, hatch, linearGradient, marker, mask, meshgradient, metadata, pattern, radialGradient, script, style and title; it also includes a symbol element that is not the instance root of a use-element shadow tree.

renderable element

Any element type that can have a direct representation in the rendering tree, as a graphic, container, text, audio, or animation. It includes the following elements: a, audio, canvas, circle, ellipse, foreignObject, g, iframe, image, line, mesh, path, polygon, polyline, rect, svg, switch, text, textPath, tspan, unknown, use and video; it also includes a symbol element that is the instance root of a use-element shadow tree.

A renderable element may or may not be rendered in a given document or point in time.

3.2.2. Rendered versus non-rendered elements

At any given time, every SVG element (or element instance in a use-element shadow tree) is either rendered or non-rendered. Whether an element is currently rendered or not affects not only its visual display but also interactivity and geometric calculations.

An element is not rendered in any of these four situations:

Non-rendered elements:

Non-rendered elements are not represented in the document accessibility tree. Nonetheless, they remain part of the document model, and participate in style inheritance and cascade.

3.2.3. Controlling visibility: the effect of the ‘display’ and ‘visibility’ properties

SVG uses two properties to toggle the visible display of elements that are normally rendered: display and visibility. Although they have a similar visible effect in static documents, they are conceptually distinct.

See the CSS 2.1 specification for the definitions of display and visibility. [CSS2]

Setting display to none results in the element not being rendered. When applied to graphics elements, text content elements, and container elements that are normally rendered, setting display to none results in the element (and all its descendents) not becoming part of the rendering tree. Note that display is not an inherited property.

Elements that have any other display value than none are rendered as normal.

The display property only applies to renderable elements. Setting display: none on an element that is never directly rendered or not rendered based on conditional processing has no effect.

The display property affects the direct processing of a given element, but it does not prevent it from being referenced by other elements. For example, setting display: none on a path element will prevent that element from getting rendered directly onto the canvas, but the path element can still be referenced by a textPath element and its geometry will be used in text-on-a-path processing.

When applied to a graphics element or use element, setting visibility to hidden or collapse results in the element not being painted. It is, however, still part of the rendering tree. It may be sensitive to pointer events (depending on the value of pointer-events), may receive focus (depending on the value of tabindex), contributes to bounding box calculations and clipping paths, and does affect text layout.

The visibility property only directly applies to graphics elements, text content elements (including the a element when it is a child of text content element) and use elements. Since visibility is an inherited property, however, although it has no effect on a use element or container element itself, its inherited value can affect descendant elements.

3.2.4. Re-used graphics

Graphical content defined in one part of the document (or in another document) may be used to render other elements. There are two types of re-used graphics from a rendering perspective:

Shadow DOM elements are rendered in the same way as normal elements, as if the host element (e.g., the use element) was a container and the shadow content was its descendents. Style and geometry properties on the shadow DOM elements are resolved independently from those on their corresponding element in the source document. The display property has its normal effect on shadow elements, except for special rules that apply to the symbol element.

Unless properties on the host element create a stacking context, z-index values on shadow DOM elements can change their rendering order relative to elements in the main DOM. For blending purposes, the use element forms a non-isolated group.

In contrast, graphical effects elements generate a self-contained SVG fragment which is rendered independently as a stacking context and an isolated group. The canvas for this fragment is scaled The graphical effect element's child content is rendered and composited into this canvas. The flattened canvas as a whole is treated as a vector image when compositing and blending with other paint layers

The display property on any child content of a graphical effects element has its normal effect when set to none, excluding that subtree from being used in rendering. However, the graphical effect is not altered by a value of display: none on the graphical effect element or an ancestor.

3.3. The painters model

SVG uses a "painters model" of rendering. Paint is applied in successive operations to the output device such that each operation paints onto some area of the output device, possibly obscuring paint that has previously been layed down. After each object or group is painted, it becomes part of the background for the next painting operation. SVG 2 supports advanced blending modes and compositing operations that control how each painting operation interacts with the background. The rules governing these painting operations are outlined in the Compositing and Blending Specification.

3.4. Rendering order

Elements in SVG are positioned in three dimensions. In addition to their position on the x and y axis of the SVG viewport, SVG elements are also positioned on the z axis. The position on the z-axis defines the order that they are painted.

Along the z axis, elements are grouped into stacking contexts, each stacking context has an associated stack level. A stack level may contain one or more child nodes - either child stack levels, graphics elements, or g elements. graphics elements and g elements within single stack level are painted in document order - that is, they are painted in the order that they are defined in the document.

Each stack level is assigned an integer value that defines it's position on the z axis relative to other stack levels within the same stacking context. Lower values are painted first, and so elements in a stack level with a higher value will paint over one with a lower value.

By default, everything is placed in stack level zero.

3.4.1. Controlling element rendering order: the ‘z-index’ property

This feature is at risk.

See the CSS 2.1 specification for the definition of z-index. [CSS2]

The z-index property allows an element to be assigned to a stack level.

The rules governing behavior for SVG elements with the z-index property specified are outlined below:

CSS specifies a property named z-index. The CSS rules that define the effect of the ‘z-index’ property were written specifically for the CSS box model, and those rules do not make sense as they stand for most SVG elements (most SVG elements do not participate in or establish a CSS box model layout). This section specifies how implementations must handle the z-index property on elements in the SVG namespace.

Contrary to the rules in CSS 2.1, the z-index property applies to all SVG elements regardless of the value of the position property, with one exception: as for boxes in CSS 2.1, outer svg elements must be positioned for z-index to apply to them.

The z-index property specifies:

  1. The stack level of the element in the current stacking context.
  2. Whether the element establishes a new local stacking context.

Values have the following meanings:

<integer>
This integer is the stack level of the element in the current stacking context. The element also establishes a new local stacking context for its descendants.
auto
The stack level of the element in the current stacking context is the same as its parent element, unless its parent established a new stacking context, in which case its stack level is 0. The element does not establish a new local stacking context.

Here is a simple example:

<svg xmlns="http://www.w3.org/2000/svg">
  <rect x="0"  width="100" height="100" style="fill: red;    z-index: -1;"/>
  <rect x="40" width="100" height="100" style="fill: lime;"/>
  <rect x="80" width="100" height="100" style="fill: blue;   z-index: 1;/>
  <rect x="60" width="100" height="100" style="fill: aqua;"/>
  <rect x="20" width="100" height="100" style="fill: yellow; z-index: -1;"/>
</svg>

In this example there are three stack levels: -1, 0 (the default) and 1. The red and yellow rects are in stack level -1, the lime and aqua rects are in stack level 0 (the default), and the blue rect is in stack level 1. Going from lowest stack level to highest, and painting the elements in each stack level in document order, the painting order is: red, yellow, lime, aqua, blue.

3.4.2. Establishing a stacking context in SVG

A new stacking context must be established at an SVG element for its descendants if:

Stacking contexts and stack levels are conceptual tools used to describe the order in which elements must be painted one on top of the other when the document is rendered, and for determining which element is highest when determining the target of a pointer event. Stacking contexts and stack levels do not affect the position of elements in the DOM tree, and their presence or absence does not affect an element's position, size or orientation in the canvas' X-Y plane - only the order in which it is painted.

Stacking contexts can contain further stacking contexts. A stacking context is atomic from the point of view of its parent stacking context; elements in ancestor stacking contexts may not come between any of its elements.

Each element belongs to one stacking context. Each element in a given stacking context has an integer stack level. Elements with a higher stack level must be placed in front of elements with lower stack levels in the same stacking context. Elements may have negative stack levels. Elements with the same stack level in a stacking context must be stacked according to document order.

With the exception of the foreignObject element, the back to front stacking order for a stacking context created by an SVG element is:

  1. the background and borders of the element forming the stacking context, if any
  2. child stacking contexts created by descendants with negative stack levels, primarily ordered by most negative first, then by tree order
  3. descendants with 'z-index: auto' or 'z-index: 0', in tree order
  4. child stacking contexts created by descendants with positive stack levels, primarily ordered by lowest index first, then by tree order

Since the foreignObject element creates a "fixed position containing block" in CSS terms, the normative rules for the stacking order of the stacking context created by foreignObject elements are the rules in Appendix E of CSS 2.1.

In the following example, the z-index property on the g element is set to zero. This creates a new stacking context to contain the g element's children without moving the g to a different level in the document's root stacking context:

<svg xmlns="http://www.w3.org/2000/svg">
  <g style="z-index: 0;">
    <!-- this is a self contained graphic -->
    <rect x="40" width="100" height="100" style="fill: lime; z-index: 1;"/>
    <rect x="20" width="100" height="100" style="fill: yellow;"/>
  </g>
  <rect x="60" width="100" height="100" style="fill: aqua;"/>
  <rect x="0" width="100" height="100" style="fill: red; z-index: -1;"/>
</svg>

The example's root stacking context contains two stack levels: -1 and 0. The red rect is in level -1, and the g element and aqua rect are in level 0. Inside stack level 0, the g element's z-index property creates a new nested stacking context at the g for the g element's children. In this child stacking context there are two stack levels: 0 and 1. The yellow rect is in level 0 (the default), and the lime rect is in level 1.

Painting of this example starts with the stack levels of the root stacking context. First the red rect is painted in level -1, then in level 0 the g element is painted followed by the aqua rect. When the g element is painted, the child stacking context that its z-index created and all of that context's stack levels are also painted. In this child stacking context, first the yellow rect in level 0 is painted, followed by the lime rect in level 1. It's only after the g and the stacking context that it creates has been painted that the aqua rect is painted. Note that this means that although the z-index of 1 for the lime rect is a higher value than the (implicit) z-index of 0 for the aqua rect, the containment provided by the g's child stacking context results in the aqua rect painting over the lime rect. The painting order is therefore: red, yellow, lime, aqua.

3.5. How elements are rendered

Individual graphics elements are treated as if they are a non-isolated group, the components (fill, stroke, etc) that make up a graphic element (See Painting shapes and text) being members of that group. See How groups are rendered.

3.6. How groups are rendered

Grouping elements, such as the g element (see container elements ) create a compositing group. Similarly, a use element creates a compositing group for its shadow content. The Compositing and Blending specification normatively describes how to render compositing groups. In SVG, effects may be applied to a group. For example, opacity, filters or masking. These effects are applied to the rendered result of the group immediately before any transforms on the group are applied, which are applied immediately before the group is blended and composited with the group backdrop. Applying any such effects to a group makes that group isolated.

Thus, rendering a compositing group follows the following steps:
If the group is isolated:

  1. The initial backdrop is set to a new buffer initialised with rgba(0,0,0,0)
  2. The contents of the group that are graphics elements or g elements are rendered in order, onto the initial backdrop
  3. filters and other effects that modify the group canvas are applied

    To provide for high quality rendering, filter primitives and other bitmap effects must be applied in the operating coordinate space.

  4. Group transforms are applied
  5. The group canvas is blended and composited with the group backdrop
else (the group is not isolated):
  1. The initial backdrop is set to the group backdrop
  2. The contents of the group that are graphics elements or g elements are rendered in order, onto the initial backdrop. The group transforms are applied to each element as they are rendered.

3.6.1. Object and group opacity: the effect of the ‘opacity’ property

See the CSS Color Module Level 3 for the definition of opacity. [css3-color]

The opacity property specifies how opaque a given graphical element or container element will be when it is painted to the canvas. When applied to a container element, this is known as group opacity, and when applied to an individual rendering element, it is known as object opacity. The principle for these two operations however is the same.

There are several other opacity-related properties in SVG:

These four opacity properties are involved in intermediate rendering operations. Object and group opacity however can be thought of as a post-processing operation. Conceptually, the object or group to which opacity applies is rendered into an RGBA offscreen image. The offscreen image as whole is then blended into the canvas with the specified opacity value used uniformly across the offscreen image. Thus, the presence of opacity causes the group to be isolated.

The opacity property applies to the following SVG elements: svg, g, symbol, marker, a, switch, use, unknown and graphics elements.

The following example illustrates various usage of the opacity property on objects and groups.

<svg xmlns="http://www.w3.org/2000/svg"
     width="600" height="175" viewBox="0 0 1200 350">

  <!-- Background blue rectangle -->
  <rect x="100" y="100" width="1000" height="150" fill="blue"/>

  <!-- Red circles going from opaque to nearly transparent -->
  <circle cx="200" cy="100" r="50" fill="red" opacity="1"/>
  <circle cx="400" cy="100" r="50" fill="red" opacity=".8"/>
  <circle cx="600" cy="100" r="50" fill="red" opacity=".6"/>
  <circle cx="800" cy="100" r="50" fill="red" opacity=".4"/>
  <circle cx="1000" cy="100" r="50" fill="red" opacity=".2"/>

  <!-- Opaque group, opaque circles -->
  <g opacity="1">
    <circle cx="182.5" cy="250" r="50" fill="red" opacity="1"/>
    <circle cx="217.5" cy="250" r="50" fill="green" opacity="1"/>
  </g>
  <!-- Group opacity: .5, opacity circles -->
  <g opacity=".5">
    <circle cx="382.5" cy="250" r="50" fill="red" opacity="1"/>
    <circle cx="417.5" cy="250" r="50" fill="green" opacity="1"/>
  </g>
  <!-- Opaque group, semi-transparent green over red -->
  <g opacity="1">
    <circle cx="582.5" cy="250" r="50" fill="red" opacity=".5"/>
    <circle cx="617.5" cy="250" r="50" fill="green" opacity=".5"/>
  </g>
  <!-- Opaque group, semi-transparent red over green -->
  <g opacity="1">
    <circle cx="817.5" cy="250" r="50" fill="green" opacity=".5"/>
    <circle cx="782.5" cy="250" r="50" fill="red" opacity=".5"/>
  </g>
  <!-- Group opacity .5, semi-transparent green over red -->
  <g opacity=".5">
    <circle cx="982.5" cy="250" r="50" fill="red" opacity=".5"/>
    <circle cx="1017.5" cy="250" r="50" fill="green" opacity=".5"/>
  </g>
</svg>
Image showing different groups of circles blended into the background.

Each group of red and green circles is first rendered to an offscreen image before being blended with the background blue rectangle as a whole, with the given opacity values.

In the example, the top row of circles have differing opacities, ranging from 1.0 to 0.2. The bottom row illustrates five g elements, each of which contains overlapping red and green circles, as follows:

3.7. Types of graphics elements

SVG supports three fundamental types of graphics elements that can be rendered onto the canvas:

3.7.1. Painting shapes and text

Shapes and text can be filled (i.e., apply paint to the interior of the shape) and stroked (i.e., apply paint along the outline of the shape).

For certain types of shapes, marker symbols (which themselves can consist of any combination of shapes, text and images) can be drawn at positions along the shape boundary. Each marker symbol is painted as if its graphical content were expanded into the SVG document tree just after the shape object which is using the given marker symbol. The graphical contents of a marker symbol are rendered using the same methods as graphics elements. Marker symbols are not applicable to text.

The order in which fill, stroke and markers are painted is determined by the paint-order property. The default is that fill is painted first, then the stroke, and then the marker symbols. The marker symbols are rendered in order along the outline of the shape, from the start of the shape to the end of the shape.

The fill and stroke operations are entirely independent painting operations. Each fill and stroke operation has its own opacity settings; thus, you can fill and/or stroke a shape with a semi-transparently drawn solid color, with different opacity values for the fill and stroke operations.

SVG supports numerous built-in types of paint which can be used in fill and stroke operations. These are described in Paint Servers.

3.7.2. Painting raster images

When a raster image is rendered, the original samples are "resampled" using standard algorithms to produce samples at the positions required on the output device. Resampling requirements are discussed under conformance requirements.

As in HTML [HTML, 10.4.2], all animated images with the same absolute URL and the same image data are expected to be rendered synchronised to the same timeline as a group, with the timeline starting at the time of the least recent addition to the group.

When a user agent is to restart the animation for an img element showing an animated image, all animated images with the same absolute URL and the same image data in that img element's node document are expected to restart their animation from the beginning.

3.8. Filtering painted regions

SVG allows any painting operation to be filtered. (See Filter Effects.)

In this case the result must be as though the paint operations had been applied to an intermediate canvas initialized to transparent black, of a size determined by the rules given in Filter Effects then filtered by the processes defined in Filter Effects.

3.9. Clipping and masking

SVG supports the following clipping/masking features:

Both, clipping and masking, are specified in the module CSS Masking [css-masking-1].

3.10. Parent compositing

SVG document fragments can be semi-opaque.

In accordance with the Compositing and Blending specification, the svg element always creates an isolated group. When an SVG document is a top-level document, meaning it is not embedded in another document, the root svg element is considered to be the page group and is composited with a backdrop of white with 100% opacity. In all other cases, the SVG document or document fragment is composited into the parent document with opacity preserved.

3.11. The effect of the ‘overflow’ property

See the Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification [CSS2] for the definition of overflow.

A summary of the behavior of the overflow property in SVG.
element initial ua stylesheet auto visible hidden scroll
document root svgvisiblen/avisible | scrollvisiblehiddenscroll
other svgvisiblehiddenvisible | scrollvisiblehiddenscroll
meshvisiblen/avisiblevisiblehiddenhidden
textvisiblehiddenvisiblevisiblehiddenhidden
patternvisiblehiddenvisiblevisiblehiddenhidden
hatchesvisiblehiddenvisiblevisiblehiddenhidden
markervisiblehiddenvisiblevisiblehiddenhidden
symbolvisiblehiddenvisiblevisiblehiddenhidden
imagevisiblehiddenvisiblevisiblehiddenhidden
iframevisiblehiddenvisible | scrollvisiblehiddenscroll
foreignObjectvisiblehiddenvisible | scrollvisiblehiddenscroll

The overflow property has the same parameter values and has the same meaning as defined in CSS 2.1 ([CSS2], section 11.1.1); however, the following additional points apply:

Although the initial value for overflow is auto. In the User Agent style sheet, overflow is overriden for the svg element when it is not the root element of a stand-alone document, the pattern element, hatch element, and the marker element to be hidden by default.

Chapter 4: Basic Data Types and Interfaces

4.1. Definitions

initial value

The initial value of an attribute or property is the value used when that attribute or property is not specified, or when it has an invalid value. This value is to be used for the purposes of rendering, calculating animation values, and when accessing the attribute or property via DOM interfaces.

invalid value
An invalid value specified for a property, either in a style sheet or a presentation attribute, is one that is either not allowed according to the grammar defining the property's values, or is allowed by the grammar but subsequently disallowed in prose. A CSS declaration with an invalid value is ignored; see Declarations and properties ([CSS2], section 4.1.8).

4.2. Attribute syntax

In this specification, attributes are defined with an attribute definition table, which looks like this:

Name Value Initial value Animatable
exampleattr <length> | none none yes

In the Value column is a description of the attribute's syntax. There are six methods for describing an attribute's syntax:

  1. Using the CSS Value Definition Syntax [css-values]. This is the notation used to define the syntax for most attributes in this specification and is the default.
  2. By reference to an EBNF symbol defined in this or another specification [xml]. For external definitions, this is indicated by [EBNF] appearing in the Value column.
  3. By reference to an ABNF symbol defined in another specification [rfc5234]. This is indicated by [ABNF] appearing in the Value column.
  4. As a URL as defined by the URL Standard [URL]. This is indicated by [URL] appearing in the Value column.
  5. As a type as defined by the HTML Standard [HTML]. This is indicated by [HTML] appearing in the Value column.
  6. In prose, below the attibute definition table. This is indicated by the text "(see below)" appearing in the Value column.
SVG 2 Requirement: Consider relaxing case sensitivity of presentation attribute values.
Resolution: We will make property values case insensitivity.
Purpose: To align presentation attribute syntax parsing with parsing of the corresponding CSS property.
Owner: Cameron (ACTION-3276)
Status: Done

When a presentation attribute defined using the CSS Value Definition Syntax is parsed, this is done as follows:

  1. Let value be the value of the attribute.
  2. Let grammar be the grammar given in the attribute definition table's Value column.
  3. Replace all instances of <length> in grammar with [<length> | <number>].
  4. Replace all instances of <angle> in grammar with [<angle> | <number>].
  5. Return the result of parsing value with grammar.

The insertion of the <number> symbols allows for unitless length and angles to be used in presentation attribute while disallowing them in corresponding property values.

Note that all presentation attributes, since they are defined by reference to their corresponding CSS properties, are defined using the CSS Value Definition Syntax.

When any other attribute defined using the CSS Value Definition Syntax is parsed, this is done by parsing the attribute's value according to the grammar given in attribute definition table.

Note that this allows CSS comments and escapes to be used in such attributes. For example, a value of '10\px/**/' would successfully parse as '10px' in the ‘x’ presentation attribute of the rect element.

When an attribute defined as a URL is parsed, this is done by invoking the URL parser with the attribute's value as input and the document's URL as base [URL].

The Initial value column gives the initial value for the attribute. When an attribute fails to parse according to the specified CSS Value Definition Syntax, ABNF or EBNF grammar, or if parsing according to the URL Standard or by the prose describing how to parse the attribute indicates failure, the attribute is assumed to have been specified as the given initial value.

The initial value of a presentation attribute is its corresponding property's initial value. Since the use of an invalid value in a presentation attribute will be treated as if the initial value was specified, this value can override values that come from lower priority style sheet rules, such as those from the user agent style sheet.

For example, although the user agent style sheet sets the value of the overflow property to hidden for svg elements, specifying an invalid presentation attribute such as overflow="invalid" will result in a rule setting overflow to visible, overriding the user agent style sheet value.

The Animatable column indicates whether the attribute can be animated using animation elements as defined in the SVG Animation module.

4.3. Real number precision

Unless stated otherwise, numeric values in SVG attributes and in properties that are defined to have an effect on SVG elements must support at least all finite single-precision values supported by the host architecture.

It is recommended that higher precision floating point storage and computation be performed on operations such as coordinate system transformations to provide the best possible precision and to prevent round-off errors.

conforming SVG viewers are required to perform numerical computation in accordance with their conformance class, as described in Conformance Criteria.

4.4. DOM interfaces for SVG elements

4.4.1. Interface SVGElement

All of the SVG DOM interfaces that correspond directly to elements in the SVG language (such as the SVGPathElement interface for the path element) derive from the SVGElement interface.

The CSSOM specification augments SVGElement with a style IDL attribute, so that the style attribute can be accessed in the same way as on HTML elements.

interface SVGElement : Element {

  [SameObject] readonly attribute SVGAnimatedString className;

  [SameObject] readonly attribute DOMStringMap dataset;

  readonly attribute SVGSVGElement? ownerSVGElement;
  readonly attribute SVGElement? viewportElement;

  attribute long tabIndex;
  void focus();
  void blur();
};

SVGElement implements GlobalEventHandlers;
SVGElement implements SVGElementInstance;

The className IDL attribute reflects the class attribute.

This attribute is deprecated and may be removed in a future version of this specification. Authors are advised to use Element.classList intead.

The dataset IDL attribute provides access to custom data attributes on the element. Its behavior is the same as the corresponding IDL member on the HTMLElement interface.

The ownerSVGElement IDL attribute represents the nearest ancestor svg element. On getting ownerSVGElement, the nearest ancestor svg element is returned; if the current element is the outermost svg element, then null is returned.

The viewportElement IDL attribute represents the element that provides the SVG viewport for the current element. On getting viewport, the nearest ancestor element that establishes an SVG viewport is returned; if the current element is the outermost svg element, then null is returned.

The tabIndex IDL attribute and the focus and blur methods are used to control focus on SVG elements in the document. Their behavior is the same as the corresponding IDL members on the HTMLElement interface.

As in HTML documents, the use of the blur method is discouraged. Authors are recommended to focus another element instead.

Authors are strongly suggested not to use the blur method or any other technique to hide the focus ring from keyboard users, such as using a CSS rule to override the outline property. Removal of the focus ring leads to serious accessibility issues for users who navigate and interact with interactive content using the keyboard.

4.4.2. Interface SVGGraphicsElement

SVG 2 Requirement: Detect if a mouse event is on the fill or stroke of a shape.
Resolution: SVG 2 will make it easier to detect if an mouse event is on the stroke or fill of an element.
Purpose: To allow authors to discriminate between pointer events on the fill and stroke of an element without having to duplicate the element
Owner: Cameron (ACTION-3279)
Status: Done.

The SVGGraphicsElement interface represents SVG elements whose primary purpose is to directly render graphics into a group.

dictionary SVGBoundingBoxOptions {
  boolean fill = true;
  boolean stroke = false;
  boolean markers = false;
  boolean clipped = false;
};

interface SVGGraphicsElement : SVGElement {
  [SameObject] readonly attribute SVGAnimatedTransformList transform;

  DOMRect getBBox(optional SVGBoundingBoxOptions options);
  DOMMatrix? getCTM();
  DOMMatrix? getScreenCTM();
};

SVGGraphicsElement implements SVGTests;

The transform IDL attribute reflects the computed value of the transform property and its corresponding ‘transform’ presentation attribute.

The getBBox method is used to compute the bounding box of the current element. When the getBBox(options) method is called, the bounding box algorithm is invoked for the current element, with fill, stroke, markers and clipped members of the options dictionary argument used to control which parts of the element are included in the bounding box, using the element's local coordinate system as the coordinate system to return the bounding box in. A newly created DOMRect object that defines the computed bounding box is returned.

The getCTM method is used to get the matrix that transforms the current element's coordinate system to its SVG viewport's coordinate system. When getCTM() is called, the following steps are run:

  1. If the current element is not in the document, then return null.
  2. Let ctm be a matrix determined based on what the current element is:
    the current element is the outermost svg element
    ctm is a matrix that transforms the coordinate space of the svg (including its transform property) to the coordinate space of the document's viewport. The matrix includes the transforms produced by the viewBox and preserveAspectRatio attributes, the transform property, and any transform due to currentScale and currentTranslate properties on the SVGSVGElement.
    any other element
    ctm is a matrix that transforms the coordinate space of the current element (including its transform property) to the coordinate space of its closest ancestor viewport-establishing element (also including its transform property).
  3. Return a newly created, detached DOMMatrix object that represents the same matrix as ctm.

The getScreenCTM method is used to get the matrix that transforms the current element's coordinate system to the coordinate system of the SVG viewport for the SVG document fragment. When getScreenCTM() is called, the following steps are run:

  1. If the current element is not in the document, then return null.
  2. Let ctm be a matrix that transforms the coordinate space of the current element (including its transform property) to the coordinate space of the document's viewport.

    This will include:

  3. Return a newly created, detached DOMMatrix object that represents the same matrix as ctm.

This method would have been more aptly named as getClientCTM, but the name getScreenCTM is kept for historical reasons.

4.4.3. Interface SVGGeometryElement

Interface SVGGeometryElement represents SVG elements whose rendering is defined by geometry with an equivalent path, and which can be filled and stroked. This includes paths and the basic shapes.

interface SVGGeometryElement : SVGGraphicsElement {
  [SameObject] readonly attribute SVGAnimatedNumber pathLength;

  boolean isPointInFill(DOMPoint point);
  boolean isPointInStroke(DOMPoint point);
  float getTotalLength();
  DOMPoint getPointAtLength(float distance);
};

The isPointInFill and isPointInStroke methods determine whether a given point is within the fill or stroke shape of an element. Normal hit testing rules apply; the value of the pointer-events property on the element determines whether a point is considered to be within the fill or stroke. The point argument is interpreted as a point in the local coordiante system of the element.

The pathLength IDL attribute reflects the pathLength content attribute.

The getTotalLength method is used to compute the length of the path. When getTotalLength() is called, the user agent's computed value for the total length of the path, in user units, is returned.

The user agent's computed path length does not take the pathLength attribute into account.

The getPointAtLength method is used to return the point at a given distance along the path. When getPointAtLength(distance) is called, the following steps are run:

  1. Let length be the user agent's computed value for the total length of the path, in user units.

    As with getTotalLength, this does not take into account the pathLength attribute.

  2. Clamp distance to [0, length].
  3. Let (x, y) be the point on the path at distance distance.
  4. Return a newly created, detached DOMPoint object representing the point (x, y).

4.5. DOM interfaces for basic data types

4.5.1. Interface SVGNumber

The SVGNumber interface is used primarily to represent a <number> value that is a part of an SVGNumberList. Individual SVGNumber objects can also be created by script.

An SVGNumber object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown, as described below. SVGNumber objects reflected through the animVal IDL attribute are always read only.

An SVGNumber object can be associated with a particular element. The associated element is used to determine which element's content attribute to update if the object reflects an attribute. Unless otherwise described, an SVGNumber object is not associated with any element.

Every SVGNumber object operates in one of two modes. It can:

  1. reflect an element of the base value of a reflected animatable attribute (being exposed through the methods on the baseVal member of an SVGAnimatedNumberList),
  2. be detached, which is the case for SVGNumber objects created with createSVGNumber.

An SVGNumber object maintains an internal number value, which is called its value.

interface SVGNumber {
  attribute float value;
};

The value IDL attribute represents the number. On getting value, the SVGNumber's value is returned.

On setting value, the following steps are run:

  1. If the SVGNumber is read only, then throw a NoModificationAllowedError.
  2. Set the SVGNumber's value to the value being assigned to the value member.
  3. If the SVGNumber reflects an element of the base value of a reflected attribute, then reserialize the reflected attribute.

4.5.2. Interface SVGLength

The SVGLength interface is used to represent a value that can be a <length>, <percentage> or <number> value.

An SVGLength object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown, as described below. SVGLength objects reflected through the animVal IDL attribute are always read only.

An SVGLength object can be associated with a particular element, as well as being designated with a directionality: horizontal, vertical or unspecified. The associated element and the directionality of the length are used to resolve percentage values to user units and is also used to determine which element's content attribute to update if the object reflects an attribute. Unless otherwise described, an SVGLength object is not associated with any element and has unspecified directionality.

Every SVGLength object operates in one of four modes. It can:

  1. reflect the base value of a reflected animatable attribute (being exposed through the baseVal member of an SVGAnimatedLength),
  2. reflect a presentation attribute value (such as by SVGRectElement.width.baseVal),
  3. reflect an element of the base value of a reflected animatable attribute (being exposed through the methods on the baseVal member of an SVGAnimatedLengthList), or
  4. be detached, which is the case for SVGLength objects created with createSVGLength.

An SVGLength object maintains an internal <length> or <percentage> or <number> value, which is called its value.

interface SVGLength {

  // Length Unit Types
  const unsigned short SVG_LENGTHTYPE_UNKNOWN = 0;
  const unsigned short SVG_LENGTHTYPE_NUMBER = 1;
  const unsigned short SVG_LENGTHTYPE_PERCENTAGE = 2;
  const unsigned short SVG_LENGTHTYPE_EMS = 3;
  const unsigned short SVG_LENGTHTYPE_EXS = 4;
  const unsigned short SVG_LENGTHTYPE_PX = 5;
  const unsigned short SVG_LENGTHTYPE_CM = 6;
  const unsigned short SVG_LENGTHTYPE_MM = 7;
  const unsigned short SVG_LENGTHTYPE_IN = 8;
  const unsigned short SVG_LENGTHTYPE_PT = 9;
  const unsigned short SVG_LENGTHTYPE_PC = 10;

  readonly attribute unsigned short unitType;
           attribute float value;
           attribute float valueInSpecifiedUnits;
           attribute DOMString valueAsString;

  void newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits);
  void convertToSpecifiedUnits(unsigned short unitType);
};

The numeric length unit type constants defined on SVGLength are used to represent the type of an SVGLength's value. Their meanings are as follows:

ConstantMeaning
SVG_LENGTHTYPE_NUMBERA unitless <number> interpreted as a value in px.
SVG_LENGTHTYPE_PERCENTAGEA <percentage>.
SVG_LENGTHTYPE_EMSA <length> with an em unit.
SVG_LENGTHTYPE_EXSA <length> with an ex unit.
SVG_LENGTHTYPE_PXA <length> with a px unit.
SVG_LENGTHTYPE_CMA <length> with a cm unit.
SVG_LENGTHTYPE_MMA <length> with a mm unit.
SVG_LENGTHTYPE_INA <length> with an in unit.
SVG_LENGTHTYPE_PTA <length> with a pt unit.
SVG_LENGTHTYPE_PCA <length> with a pc unit.
SVG_LENGTHTYPE_UNKNOWNSome other type of value.

The use of numeric length unit type constants is an anti-pattern and new constant values will not be introduced for any other units or length types supported by SVGLength. If other types of lengths are supported and used, the SVGLength uses the SVG_LENGTHTYPE_UNKNOWN unit type. See below for details on how the other properties of an SVGLength operate with these types of lengths.

The unitType IDL attribute represents the type of value that the SVGLength's value is. On getting unitType, the following steps are run:

  1. If the SVGLength's value is a unitless <number>, a <percentage>, or a <length> with an em, ex, px, cm, mm, in, pt or pc unit, then return the corresponding constant value from the length unit type table above.
  2. Otherwise, return SVG_LENGTHTYPE_UNKNOWN.

    For example, for a <length> with a ch unit or one that has a non-scalar value such as calc(), SVG_LENGTHTYPE_UNKNOWN would be returned.

The value IDL attribute represents the SVGLength's value in user units. On getting value, the following steps are run:

  1. Let value be the SVGLength's value.
  2. If value is a <number>, return that number.
  3. Let viewport size be a basis to resolve percentages against, based on the SVGLength's associated element and directionality:
    has no associated element
    size is 100
    has an associated element and horizontal directionality
    size is the width of the associated element's SVG viewport
    has an associated element and vertical directionality
    size is the height of the associated element's SVG viewport
    has an associated element and unspecified directionality
    size is the length of the associated element's SVG viewport diagonal (see Units)
  4. Let font size be a basis to resolve font size values against, based on the SVGLength's associated element:
    has no associated element
    font size is the absolute length of the initial value of the font-size property
    has an associated element
    size is the computed value of the associated element's font-size property
  5. Return the result of converting value to an absolute length, using viewport size and font size as percentage and font size bases. If the conversion is not possible due to the lack of an associated element, return 0.

On setting value, the following steps are run:

  1. If the SVGLength object is read only, then throw a NoModificationAllowedError.
  2. Let value be the value being assigned to value.
  3. Set the SVGLength's value to a <number> whose value is value.
  4. If the SVGLength reflects the base value of a reflected attribute, reflects a presentation attribute, or reflects an element of the base value of a reflected attribute, then reserialize the reflected attribute.

The valueInSpecifiedUnits IDL attribute represents the numeric factor of the SVGLength's value. On getting valueInSpecifiedUnits, the following steps are run:

  1. Let value be the SVGLength's value.
  2. If value is a <number>, return that number.
  3. Otherwise, if value is a <percentage> or any scalar <length> value, return the numeric factor before its unit.
  4. Otherwise, return 0.

    Thus valueInSpecifiedUnits would return 12 for both '12%' and 12em, but 0 would be returned for non-scalar values like calc(12px + 5%).

On setting valueInSpecifiedUnits, the following steps are run:

  1. If the SVGLength object is read only, then throw a NoModificationAllowedError.
  2. Let value be the value being assigned to valueInSpecifiedUnits.
  3. If the SVGLength's value is a <number>, then update its value to value.
  4. Otherwise, if the SVGLength's value is a <percentage> or a scalar-valued <length>, then update its numeric factor to value.
  5. Otherwise, the SVGLength's value is of some other type. Set it to a <number> whose value is value.
  6. If the SVGLength reflects the base value of a reflected attribute or reflects an element of the base value of a reflected attribute, then reserialize the reflected attribute.

The valueAsString IDL attribute represents the SVGLength's value as a string. On getting valueAsString, the following steps are run:

  1. Let value be the SVGLength's value.
  2. Let string be an empty string.
  3. If value is a <number>, <percentage> or scalar <length> value, then:
    1. Let factor be value's numeric factor, if it is a <percentage> or <length>, or value itself it is a <number>.
    2. Append to string an implementation specific string that, if parsed as a <number> using CSS syntax, would return the number value closest to factor, given the implementation's supported real number precision.
    3. If value is a <percentage> then append to string a single U+0025 PERCENT SIGN character.
    4. Otherwise, if value is a <length>, then append to string the canonical spelling of value's unit.
    5. Return string.
  4. Otherwise, return an implementation specific string that, if parsed as a <length>, would return the closest length value to value, given the implementation's supported real number precision.

On setting valueAsString, the following steps are run:

  1. If the SVGLength object is read only, then throw a NoModificationAllowedError.
  2. Let value be the value being assigned to valueAsString.
  3. Parse value using the CSS syntax [ <number> | <length> | <percentage> ].
  4. If parsing failed, then throw a SyntaxError.
  5. Otherwise, parsing succeeded. Set SVGLength's value to the parsed value.
  6. If the SVGLength reflects the base value of a reflected attribute or reflects an element of the base value of a reflected attribute, then reserialize the reflected attribute.

The newValueSpecifiedUnits method is used to set the SVGLength's value in a typed manner. When newValueSpecifiedUnits(unitType, valueInSpecifiedUnits) is called, the following steps are run:

  1. If the SVGLength object is read only, then throw a NoModificationAllowedError.
  2. If unitType is SVG_LENGTHTYPE_UNKNOWN or is a value that does not appear in the length unit type table above, then throw a NotSupportedError.
  3. Set SVGLength's value depending on the value of unitType:
    SVG_LENGTHTYPE_NUMBER
    a <number> whose value is valueInSpecifiedUnits
    SVG_LENGTHTYPE_PERCENTAGE
    a <percentage> whose numeric factor is valueInSpecifiedUnits
    anything else
    a <length> whose numeric factor is valueInSpecifiedUnits and whose unit is as indicated by the length unit type table above
  4. If the SVGLength reflects the base value of a reflected attribute or reflects an element of the base value of a reflected attribute, then reserialize the reflected attribute.

The convertToSpecifiedUnits method is used to convert the SVGLength's value to a specific type. When convertToSpecifiedUnits(unitType) is called, the following steps are run:

  1. If the SVGLength object is read only, then throw a NoModificationAllowedError.
  2. If unitType is SVG_LENGTHTYPE_UNKNOWN or is a value that does not appear in the length unit type table above, then throw a NotSupportedError.
  3. Let absolute be the value that would be returned from the value member.
  4. If unitType is SVG_LENGTHTYPE_NUMBER, then:
    1. Set the SVGLength's value to a <number> whose value is absolute.
  5. Otherwise, if unitType is SVG_LENGTHTYPE_PERCENTAGE, then:
    1. Let viewport size be a basis to resolve percentages against, based on the SVGLength's associated element and directionality:
      has no associated element
      size is 100
      has an associated element and horizontal directionality
      size is the width of the associated element's SVG viewport
      has an associated element and vertical directionality
      size is the height of the associated element's SVG viewport
      has an associated element and unspecified directionality
      size is the length of the associated element's SVG viewport diagonal (see Units)
    2. Set the SVGLength's value to the result of converting absolute to a <percentage>, using viewport size as the percentage basis.
  6. Otherwise, if unitType is SVG_LENGTHTYPE_EMS or SVG_LENGTHTYPE_EXS, then:
    1. Let font size be a basis to resolve font size values against, based on the SVGLength's associated element:
      has no associated element
      font size is the absolute length of the initial value of the font-size property
      has an associated element
      size is the computed value of the associated element's font-size property
    2. Set the SVGLength's value to the result of converting absolute to a <length> with an em or ex unit (depending on unitType), using font size as the font-size basis.
  7. Otherwise:
    1. Set the SVGLength's value to the result of converting absolute to a <length> with the unit found by looking up unitType in the length unit type table above.
  8. If the SVGLength reflects the base value of a reflected attribute or reflects an element of the base value of a reflected attribute, then reserialize the reflected attribute.

4.5.3. Interface SVGAngle

The SVGAngle interface is used to represent a value that can be an <angle> or <number> value.

An SVGAngle object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown, as described below. An SVGAngle reflected through the animVal attribute is always read only.

An SVGAngle object can be associated with a particular element. The associated element is used to determine which element's content attribute to update if the object reflects an attribute. Unless otherwise described, an SVGAngle object is not associated with any element.

Every SVGAngle object operates in one of two modes. It can:

  1. reflect the base value of a reflected animatable attribute (being exposed through the baseVal member of an SVGAnimatedAngle),
  2. be detached, which is the case for SVGAngle objects created with createSVGAngle.

An SVGAngle object maintains an internal <angle> or <number> value, which is called its value.

interface SVGAngle {

  // Angle Unit Types
  const unsigned short SVG_ANGLETYPE_UNKNOWN = 0;
  const unsigned short SVG_ANGLETYPE_UNSPECIFIED = 1;
  const unsigned short SVG_ANGLETYPE_DEG = 2;
  const unsigned short SVG_ANGLETYPE_RAD = 3;
  const unsigned short SVG_ANGLETYPE_GRAD = 4;

  readonly attribute unsigned short unitType;
           attribute float value;
           attribute float valueInSpecifiedUnits;
           attribute DOMString valueAsString;

  void newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits);
  void convertToSpecifiedUnits(unsigned short unitType);
};

The numeric angle unit type constants defined on SVGAngle are used to represent the type of an SVGAngle's value. Their meanings are as follows:

ConstantMeaning
SVG_ANGLETYPE_UNSPECIFIEDA unitless <number> interpreted as a value in degrees.
SVG_ANGLETYPE_DEGAn <angle> with a deg unit.
SVG_ANGLETYPE_RADAn <angle> with a rad unit.
SVG_ANGLETYPE_GRADAn <angle> with a grad unit.
SVG_ANGLETYPE_UNKNOWNSome other type of value.

The use of numeric angle unit type constants is an anti-pattern and new constant values will not be introduced for any other units or angle types supported by SVGAngle. If other types of angles are supported and used, the SVGAngle uses the SVG_ANGLETYPE_UNKNOWN unit type. See below for details on how the other properties of an SVGAngle operate with these types of angles.

The unitType IDL attribute represents the type of value that the SVGAngle's value is. On getting unitType, the following steps are run:

  1. If the SVGAngle's value is a unitless <number> or a <length> with a deg, rad or grad unit, then return the corresponding constant value from the angle unit type table above.
  2. Otherwise, return SVG_ANGLETYPE_UNKNOWN.

    For example, for an <angle> with a turn unit, SVG_ANGLETYPE_UNKNOWN would be returned.

The value IDL attribute represents the SVGAngle's value in user units. On getting value, the following steps are run:

  1. Let value be the SVGAngle's value.
  2. If value is a <number>, return that number.
  3. Return the result of converting value to an angle in degrees.

On setting value, the following steps are run:

  1. If the SVGAngle object is read only, then throw a NoModificationAllowedError.
  2. Let value be the value being assigned to value.
  3. Set the SVGAngle's value to a <number> whose value is value.
  4. If the SVGAngle reflects the base value of a reflected attribute, then reserialize the reflected attribute.

The valueInSpecifiedUnits IDL attribute represents the numeric factor of the SVGAngle's value. On getting valueInSpecifiedUnits, the following steps are run:

  1. Let value be the SVGAngle's value.
  2. If value is a <number>, return that number.
  3. Otherwise, value is an <angle> value. Return the numeric factor before its unit.

On setting valueInSpecifiedUnits, the following steps are run:

  1. If the SVGAngle object is read only, then throw a NoModificationAllowedError.
  2. Let value be the value being assigned to valueInSpecifiedUnits.
  3. If the SVGAngle's value is a <number>, then update its value to value.
  4. Otherwise, if the SVGAngle's value is an <angle>, then update its numeric factor to value.
  5. If the SVGAngle reflects the base value of a reflected attribute or reflects an element of the base value of a reflected attribute, then reserialize the reflected attribute.

The valueAsString IDL attribute represents the SVGAngle's value as a string. On getting valueAsString, the following steps are run:

  1. Let value be the SVGAngle's value.
  2. Let string be an empty string.
  3. Let factor be value's numeric factor, if it is an <angle>, or value itself it is a <number>.
  4. Append to string an implementation specific string that, if parsed as a <number> using CSS syntax, would return the number value closest to factor, given the implementation's supported real number precision.
  5. If value is an <angle>, then append to string the canonical spelling of value's unit.
  6. Return string.

On setting valueAsString, the following steps are run:

  1. If the SVGAngle object is read only, then throw a NoModificationAllowedError.
  2. Let value be the value being assigned to valueAsString.
  3. Parse value using the CSS syntax [ <number> | <angle> ].
  4. If parsing failed, then throw a SyntaxError.
  5. Otherwise, parsing succeeded. Set SVGAngle's value to the parsed value.
  6. If the SVGAngle reflects the base value of a reflected attribute or reflects an element of the base value of a reflected attribute, then reserialize the reflected attribute.

The newValueSpecifiedUnits method is used to set the SVGAngle's value in a typed manner. When newValueSpecifiedUnits(unitType, valueInSpecifiedUnits) is called, the following steps are run:

  1. If the SVGAngle object is read only, then throw a NoModificationAllowedError.
  2. If unitType is SVG_ANGLETYPE_UNKNOWN or is a value that does not appear in the angle unit type table above, then throw a NotSupportedError.
  3. Set SVGAngle's value depending on the value of unitType:
    SVG_ANGLETYPE_UNSPECIFIED
    a <number> whose value is valueInSpecifiedUnits
    anything else
    an <angle> whose numeric factor is valueInSpecifiedUnits and whose unit is as indicated by the angle unit type table above
  4. If the SVGAngle reflects the base value of a reflected attribute or reflects an element of the base value of a reflected attribute, then reserialize the reflected attribute.

The convertToSpecifiedUnits method is used to convert the SVGAngle's value to a specific type. When convertToSpecifiedUnits(unitType) is called, the following steps are run:

  1. If the SVGAngle object is read only, then throw a NoModificationAllowedError.
  2. If unitType is SVG_ANGLETYPE_UNKNOWN or is a value that does not appear in the angle unit type table above, then throw a NotSupportedError.
  3. Let degrees be the value that would be returned from the value member.
  4. If unitType is SVG_ANGLETYPE_UNSPECIFIED, then:
    1. Set the SVGAngle's value to a <number> whose value is degrees.
  5. Otherwise:
    1. Set the SVGAngle's value to the result of converting degrees to an <angle> with the unit found by looking up unitType in the angle unit type table above.
  6. If the SVGAngle reflects the base value of a reflected attribute or reflects an element of the base value of a reflected attribute, then reserialize the reflected attribute.

4.5.4. List interfaces

SVG 2 Requirement: Make the SVGList* interfaces a bit more like other lists/arrays.
Resolution: Add array style indexing and .length and .item to svg list types.
Purpose: To align with other array types (e.g. NodeList). Already implemented in Opera and Firefox.
Owner: Erik (ACTION-2975)
Status: Done

Some SVG attributes contain lists of values, and to represent these values there are a number of SVG DOM list interfaces, one for each required element type – SVGNumberList, SVGLengthList, SVGPointList, SVGTransformList and SVGStringList. The first four are used to represent the base and animated components of SVGAnimatedNumberList, SVGAnimatedLengthList, SVGAnimatedPoints and SVGTransformList objects, while the fifth, SVGStringList, is used to reflect a few unanimated attributes that take a list of strings.

Most list interfaces take the following form:

interface SVGNameList {

  readonly attribute unsigned long length;
  readonly attribute unsigned long numberOfItems;

  void clear();
  Type initialize(Type newItem);
  getter Type getItem(unsigned long index);
  Type insertItemBefore(Type newItem, unsigned long index);
  Type replaceItem(Type newItem, unsigned long index);
  Type removeItem(unsigned long index);
  Type appendItem(Type newItem);
  setter void (unsigned long index, Type newItem);
};

where Name is a descriptive name for the list element's ("Number", "Length", "Point", "Transform" or "String") and Type is the IDL type of the list's elements (SVGNumber, SVGLength, DOMPoint, SVGTransform or DOMString).

The SVGTransformList interface takes the above form but has two additional methods on it.

All list interface objects apart from SVGTransformList reflect the base value of a reflected content attribute. SVGTransformList objects reflect a presentation attribute (‘transform’, gradientTransform or patternTransform). All list interface objects are associated with a particular element. Unlike SVGLength and similar objects, there are no "detached" list interface objects.

A list interface object maintains an internal list of elements, which is referred to in the text below simply as "the list". The IDL attributes and methods are used to inspect and manipulate elements of the list. The list can also be changed in response to changes to the reflected content attribute and to animation of the content attribute (or, for SVGTransformList objects, in response to changes to the computed value of the transform property).

A list interface object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown, as described below. list interface objects reflected through the animVal IDL attribute are always read only.

A list interface object is synchronized by running the following steps:

  1. Let value be the base value of the reflected content attribute (using the attribute's initial value if it is not present or invalid).
  2. Let length be the number of items in the list.
  3. Let new length be the number of values in value. If value is the keyword none (as supported by the transform property), new length is 0.
  4. If the list element type is SVGNumber, SVGLength, DOMPoint or SVGTransform, then:
    1. If length > new length, then:
      1. Detach each object in the list at an index greater than or equal to new length.
      2. Truncate the list to length new length.
      3. Set length to new length.
    2. While length < new length:
      1. Let item be a newly created object of the list element type.
      2. Attach item to this list interface object.
      3. Append item to the list.
      4. Set length to length + 1.
    3. Let index be 0.
    4. While index < length:
      1. Let item be the object in the list at index index.
      2. Let v be the value in value at index index.
      3. Set item's value to v.
      4. If item is an SVGTransform object, then set the components of its matrix object to match the new transform function value.
      5. Set index to index + 1.
  5. Otherwise, the list element type is DOMString:
    1. Replace the list with a new list consisting of the values in value.

Whenever a list element object is to be detached, the following steps are run, depending on the list element type:

SVGNumber
Set the SVGNumber to no longer be associated with any element. If the SVGNumber is read only, set it to be no longer read only.
SVGLength
Set the SVGLength to no longer be associated with any element. If the SVGLength is read only, set it to be no longer read only. Set the SVGLength to have unspecified directionality.
DOMPoint
Set the DOMPoint to no longer be associated with any element. If the DOMPoint is read only, set it to be no longer read only.
SVGTransform
Set the SVGTransform to no longer be associated with any element. If the SVGTransform is read only, set it to be no longer read only.
DOMString
Nothing is done.

Whenever a list element object is to be attached, the following steps are run, depending on the list element type:

SVGNumber
Associate the SVGNumber with the element that the list interface object is associated with. Additionally, depending on which IDL attribute the list interface object is reflected through:
baseVal
Set the SVGNumber to reflect an element of the base value.
animVal
Set the SVGNumber to reflect an element of the base value.
SVGLength
Associate the SVGLength with the element that the list interface object is associated with and set its directionality to that specified by the attribute being reflected. Additionally, depending on which IDL attribute the list interface object is reflected through:
baseVal
Set the SVGLength to reflect an element of the base value.
animVal
Set the SVGLength to reflect an element of the base value. Set the SVGLength to be read only.
DOMPoint
Associate the DOMPoint with the element that the list interface object is associated with. Additionally, depending on which IDL attribute the list interface object is reflected through:
baseVal
Set the DOMPoint to reflect an element of the base value.
animVal
Set the DOMPoint to reflect an element of the base value.
SVGTransform
Associate the SVGTransform with the element that the list interface object is associated with. Set the SVGTransform to reflect an element of a presentation attribute value.
DOMString
Nothing is done.

The supported property indices of a list interface object is the set of all non-negative integers less than the length of the list.

The length and numberOfItems IDL attributes represents the length of the list, and on getting simply return the length of the list.

The clear method is used to remove all items in the list. When clear() is called, the following steps are run:

  1. If the list is read only, then throw a NoModificationAllowedError.
  2. Detach and then remove all elements in the list.
  3. If the list reflects an attribute, or represents the base value of an object that reflects an attribute, then reserialize the reflected attribute.

The initialize method is used to clear the list and add a single, specified value to it. When initialize(newItem) is called, the following steps are run:

  1. If the list is read only, then throw a NoModificationAllowedError.
  2. Detach and then remove all elements in the list.
  3. If newItem is an object type, and newItem is not a detached object, then set newItem to be a newly created object of the same type as newItem and which has the same (number or length) value.
  4. Attach newItem to the list interface object.
  5. Append newItem to this list.
  6. If the list reflects an attribute, or represents the base value of an object that reflects an attribute, then reserialize the reflected attribute.
  7. Return newItem.

The getItem method is used to get an item from the list at the specified position. When getItem(index) is called, the following steps are run:

  1. If index is greater than or equal to the length of the list, then throw an IndexSizeError.
  2. Return the element in the list at position index.

    Note that if the list's element type is an object type, such as SVGLength, then a reference to that object and not a copy of it is returned.

The insertItemBefore method is used to insert an element into the list at a specific position. When insertItemBefore(newItem, index) is called, the following steps are run:

  1. If the list is read only, then throw a NoModificationAllowedError.
  2. If newItem is an object type, and newItem is not a detached object, then set newItem to be a newly created object of the same type as newItem and which has the same (number or length) value.
  3. If index is greater than the length of the list, then set index to be the list length.
  4. Insert newItem into the list at index index.
  5. Attach newItem to the list interface object.
  6. If the list reflects an attribute, or represents the base value of an object that reflects an attribute, then reserialize the reflected attribute.
  7. Return newItem.

The replaceItem method is used to replace an existing item in the list with a new item. When replaceItem(newItem, index) is called, the following steps are run:

  1. If the list is read only, then throw a NoModificationAllowedError.
  2. If index is greater than or equal to the length of the list, then throw an IndexSizeError.
  3. If newItem is an object type, and newItem is not a detached object, then set newItem to be a newly created object of the same type as newItem and which has the same (number or length) value.
  4. Detach the element in the list at index index.
  5. Replace the element in the list at index index with newItem.
  6. Attach newItem to the list interface object.
  7. If the list reflects an attribute, or represents the base value of an object that reflects an attribute, then reserialize the reflected attribute.
  8. Return newItem.

The removeItem method is used to remove an item from the list. When removeItem(index) is called, the following steps are run:

  1. If the list is read only, then throw a NoModificationAllowedError.
  2. If index is greater than or equal to the length of the list, then throw an IndexSizeError with code.
  3. Let item be the list element at index index.
  4. Detach item.
  5. Remove the list element at index index.
  6. Return item.

The appendItem method is used to append an item to the end of the list. When appendItem(newItem) is called, the following steps are run:

  1. If the list is read only, then throw a NoModificationAllowedError.
  2. If newItem is an object type, and newItem is not a detached object, then set newItem to be a newly created object of the same type as newItem and which has the same (number or length) value.
  3. Let index be the length of the list.
  4. Append newItem to the end of the list.
  5. Attach newItem to the list interface object.
  6. If the list reflects an attribute, or represents the base value of an object that reflects an attribute, then reserialize the reflected attribute.
  7. Return newItem.

The behavior of the indexed property setter is the same as that for the replaceItem method.

4.5.5. Interface SVGNumberList

The SVGNumberList interface is a list interface whose elements are SVGNumber objects. An SVGNumberList object represents a list of numbers.

interface SVGNumberList {

  readonly attribute unsigned long length;
  readonly attribute unsigned long numberOfItems;

  void clear();
  SVGNumber initialize(SVGNumber newItem);
  getter SVGNumber getItem(unsigned long index);
  SVGNumber insertItemBefore(SVGNumber newItem, unsigned long index);
  SVGNumber replaceItem(SVGNumber newItem, unsigned long index);
  SVGNumber removeItem(unsigned long index);
  SVGNumber appendItem(SVGNumber newItem);
  setter void (unsigned long index, SVGNumber newItem);
};

The behavior of all of the interface members of SVGNumberList are defined in the List interfaces section above.

4.5.6. Interface SVGLengthList

The SVGLengthList interface is a list interface whose elements are SVGLength objects. An SVGLengthList object represents a list of lengths.

interface SVGLengthList {

  readonly attribute unsigned long length;
  readonly attribute unsigned long numberOfItems;

  void clear();
  SVGLength initialize(SVGLength newItem);
  getter SVGLength getItem(unsigned long index);
  SVGLength insertItemBefore(SVGLength newItem, unsigned long index);
  SVGLength replaceItem(SVGLength newItem, unsigned long index);
  SVGLength removeItem(unsigned long index);
  SVGLength appendItem(SVGLength newItem);
  setter void (unsigned long index, SVGLength newItem);
};

The behavior of all of the interface members of SVGLengthList are defined in the List interfaces section above.

4.6. DOM interfaces for reflecting SVG attributes

In SVG 1.1 SE, the animVal attribute of the SVG DOM interfaces represented the current animated value of the reflected attribute. In this version of SVG, animVal no longer representes the current animated value and is instead an alias of baseVal.

Some IDL attributes reflect the value of a content attribute or a property. The way this reflection is done depends on the type of the IDL attribute:

Whenever a reflected content attribute's base value changes, then the reflecting object must be synchronized, immediately after the value changed, by running the following steps:

  1. If the reflecting object is a list interface object, then run the steps for synchronizing a list interface object.
  2. Otherwise, update the object's value to be the base value of the reflected content attribute (using the attribute's initial value if it is not present or invalid).

    This will, for example, update the value of an SVGLength object.

When a reflected content attribute is to be reserialized, optionally using a specific value, the following steps must be performed:

  1. Let value be the specific value given, or the value of the content attribute's reflecting IDL attribute if a specific value was not provided.
  2. Depending on value's type:
    SVGAnimatedBoolean
    SVGAnimatedNumber
    SVGAnimatedLength
    SVGAnimatedAngle
    SVGAnimatedRect
    SVGAnimatedString
    SVGAnimatedNumberList
    SVGAnimatedLengthList
    SVGAnimatedTransformList
    Reserialize the content attribute using value's baseVal member.
    SVGAnimatedEnumeration
    1. Let number be the value of value's baseVal member.
    2. Let keyword be the content attribute's keyword value corresponding to number, or the empty string if number is 0.

      This means that if the enumeration value is set to the "unknown" value, the content attribute will be set to the empty string.

    3. Set the content attribute to keyword.
    boolean
    Set the content attribute to "true" if value is true, and "false" otherwise.
    float
    double
    Set the content attribute to an implementation specific string that, if parsed as a <number> using CSS syntax, would return the number value closest to value, given the implementation's supported real number precision.
    SVGLength
    Set the content attribute to the value that would be returned from getting value's valueAsString member.
    SVGAngle
    Set the content attribute to the value that would be returned from getting value's valueAsString member.
    DOMRect
    1. Let components be a list of four values, being the values of the x, y, width and height members of value.
    2. Let serialized components be a list of four strings, where each is an implementation specific string that, if parsed as a <number> using CSS syntax, would return the number value closest to the corresponding value in components, given the implementation's supported real number precision.
    3. Set the content attribute to a string consisting of the strings in serialized components joined and separated by single U+0020 SPACE characters.
    DOMString
    Set the content attribute to value.
    SVGNumberList
    SVGLengthList
    SVGPointList
    SVGTransformList
    SVGStringList
    1. Let elements be the list of values in value.

      The values will be SVGNumber, SVGLength, DOMPoint or SVGTransform objects, or DOMString values, depending on value's type.

    2. Let serialized elements be a list of strings, where each string is formed based on the corresponding value in elements and its type:
      an SVGNumber object
      The string is an implementation specific string that, if parsed as a <number> using CSS syntax, would return the number value closest to the SVGNumber object's value member, given the implementation's supported real number precision.
      an SVGLength object
      The string is the value that would be returned from getting the value's valueAsString member.
      a DOMPoint object
      The string value is computed as follows:
      1. Let string be an empty string.
      2. Let x and y be the values of the DOMPoint object's x and y coordinates, respectively.
      3. Append to string an implementation specific string that, if parsed as <number> using CSS syntax, would return the number value closest to x, given the implementation's supported real number precision.
      4. Append a single U+002C COMMA character to string.
      5. Append to string an implementation specific string that, if parsed as <number> using CSS syntax, would return the number value closest to y, given the implementation's supported real number precision.
      6. The string is string.
      a SVGTransform object
      The string is the serialization of the SVGTransform object's matrix object.
      a DOMString
      The string is the DOMString's value itself.
    3. Set the content attribute to a string consisting of the strings in serialized elements joined and separated by single U+0020 SPACE characters.

4.6.1. Interface SVGAnimatedBoolean

An SVGAnimatedBoolean object is used to reflect an animatable attribute that takes a boolean value.

interface SVGAnimatedBoolean {
           attribute boolean baseVal;
  readonly attribute boolean animVal;
};

The baseVal and animVal IDL attributes both represent the current non-animated value of the reflected attribute. On getting baseVal or animVal, the following steps are run:

  1. Let value be the value of the reflected attribute, or the empty string if it is not present.
  2. If value is not "true" or "false", then set value to the reflected attribute's initial value.
  3. Return true if value is "true", and false otherwise.

On setting baseVal, the reflected attribute is set to "true" if the value is true, and "false" otherwise.

4.6.2. Interface SVGAnimatedEnumeration

An SVGAnimatedEnumeration object is used to reflect an animatable attribute that takes a keyword value (such as the method attribute on textPath) or to reflect the type of value that an animatable attribute has (done only by the orientType IDL attribute for the marker element's orient attribute).

interface SVGAnimatedEnumeration {
           attribute unsigned short baseVal;
  readonly attribute unsigned short animVal;
};

For SVGAnimatedEnumeration objects that reflect an animatable attribute that takes only a keyword value, the baseVal and animVal IDL attributes represents the current non-animated value of the reflected attribute. For orientType, they represent the type of the current non-animated value of the reflected orient attribute. On getting baseVal or animVal, the following steps are run:

  1. Let value be the value of the reflected attribute (using the attribute's initial value if it is not present or invalid).
  2. Return the numeric type value for value, according to the reflecting IDL attribute's definition.

On setting baseVal, the following steps are run:

  1. Let value be the value being assigned to baseVal.
  2. If value is 0 or is not the numeric type value for any value of the reflected attribute, then set the reflected attribute to the empty string.
  3. Otherwise, if the reflecting IDL attribute is orientType and value is SVG_MARKER_ORIENT_ANGLE, then set the reflected attribute to the string "0".
  4. Otherwise, value is the numeric type value for a specific, single keyword value for the reflected attribute. Set the reflected attribute to that value.

4.6.3. Interface SVGAnimatedInteger

An SVGAnimatedInteger object is used to reflect an animatable attribute that takes an integer value (such as numOctaves on feTurbulence). It is also used to reflect one part of an animatable attribute that takes an integer followed by an optional second integer (such as order on feConvolveMatrix).

This SVGAnimatedInteger interface is not used in this specification, however the Filter Effects specification has a number of uses of it.

interface SVGAnimatedInteger {
           attribute long baseVal;
  readonly attribute long animVal;
};

For SVGAnimatedInteger objects that reflect an animatable attribute that takes a single integer value, the baseVal and animVal IDL attributes represent the current non-animated value of the reflected attribute. For those that reflect one integer of an attribute that takes an integer followed by an optional second integer, they represent the current non-animated value of one of the two integers. On getting baseVal or animVal, the following steps are run:

  1. Let value be the value of the reflected attribute (using the attribute's initial value if it is not present or invalid).
  2. If the reflected attribute is defined to take an integer followed by an optional second integer, then:
    1. If this SVGAnimatedInteger object reflects the first integer, then return the first value in value.
    2. Otherwise, this SVGAnimatedInteger object reflects the second integer. Return the second value in value if it has been explicitly specified, and if not, return the implicit value as described in the definition of the attribute.

      For example, the definition of order says that the implicit second integer is the same as the explicit first integer.

  3. Otherwise, the reflected attribute is defined to take a single integer value. Return value.

On setting baseVal, the following steps are run:

  1. Let value be the value being assigned to baseVal.
  2. Let new be a list of integers.
  3. If the reflected attribute is defined to take an integer followed by an optional second integer, then:
    1. Let current be the value of the reflected attribute (using the attribute's initial value if it is not present or invalid).
    2. Let first be the first integer in current.
    3. Let second be the second integer in current if it has been explicitly specified, and if not, the implicit value as described in the definition of the attribute.
    4. If this SVGAnimatedInteger object reflects the first integer, then set first to value. Otherwise, set second to value.
    5. Append first to new.
    6. Append second to new.
  4. Otherwise, the reflected attribute is defined to take a single integer value. Append value to new.
  5. Set the content attribute to a string consisting of each integer in new serialized to an implementation specific string that, if parsed as an <number> using CSS syntax, would return that integer, joined and separated by a single U+0020 SPACE character.

4.6.4. Interface SVGAnimatedNumber

An SVGAnimatedNumber object is used to reflect an animatable attribute that takes a number value (such as pathLength on path). It is also used to reflect one part of an animatable attribute that takes an number followed by an optional second number (such as kernelUnitLength on feDiffuseLighting).

interface SVGAnimatedNumber {
           attribute float baseVal;
  readonly attribute float animVal;
};

For SVGAnimatedNumber objects that reflect an animatable attribute that takes a single number value, the baseVal and animVal IDL attributes represent the current non-animated value of the reflected attribute. For those that reflect one number of an attribute that takes a number followed by an optional second number, they represent the current non-animated value of one of the two numbers. On getting baseVal or animVal, the following steps are run:

  1. Let value be the value of the reflected attribute (using the attribute's initial value if it is not present or invalid).
  2. If the reflected attribute is defined to take an number followed by an optional second number, then:
    1. If this SVGAnimatedNumber object reflects the first number, then return the first value in value.
    2. Otherwise, this SVGAnimatedNumber object reflects the second number. Return the second value in value if it has been explicitly specified, and if not, return the implicit value as described in the definition of the attribute.

      For example, the definition of kernelUnitLength says that the implicit second number is the same as the explicit first number.

  3. Otherwise, the reflected attribute is defined to take a single number value. Return value.

On setting baseVal, the following steps are run:

  1. Let value be the value being assigned to baseVal.
  2. Let new be a list of numbers.
  3. If the reflected attribute is defined to take an number followed by an optional second number, then:
    1. Let current be the value of the reflected attribute (using the attribute's initial value if it is not present or invalid).
    2. Let first be the first number in current.
    3. Let second be the second number in current if it has been explicitly specified, and if not, the implicit value as described in the definition of the attribute.
    4. If this SVGAnimatedNumber object reflects the first number, then set first to value. Otherwise, set second to value.
    5. Append first to new.
    6. Append second to new.
  4. Otherwise, the reflected attribute is defined to take a single number value. Append value to new.
  5. Set the content attribute to a string consisting of each number in new serialized to an implementation specific string that, if parsed as an <number> using CSS syntax, would return the value closest to the number (given the implementation's supported Precisionreal number precision), joined and separated by a single U+0020 SPACE character.

4.6.5. Interface SVGAnimatedLength

An SVGAnimatedLength object is used to reflect either (a) an animatable attribute that takes a <length>, <percentage> or <number> value, or (b) a CSS property that takes one of these values and its corresponding presentation attribute.

interface SVGAnimatedLength {
  [SameObject] readonly attribute SVGLength baseVal;
  [SameObject] readonly attribute SVGLength animVal;
};

The baseVal and animVal IDL attributes represent the current value of the reflected content attribute. On getting baseVal or animVal, an SVGLength object is returned that:

4.6.6. Interface SVGAnimatedAngle

An SVGAnimatedAngle object is used to reflect the <angle> value of the animated orient attribute on marker, through the orientAngle IDL attribute.

interface SVGAnimatedAngle {
  [SameObject] readonly attribute SVGAngle baseVal;
  [SameObject] readonly attribute SVGAngle animVal;
};

The baseVal and animVal IDL attributes represent the current non-animated <angle> value of the reflected orient attribute. On getting baseVal or animVal, an SVGAngle object is returned that:

4.6.7. Interface SVGAnimatedString

An SVGAnimatedString object is used to reflect an animatable attribute that takes a string value. It can optionally be defined to additionally reflect a second, deprecated attribute.

interface SVGAnimatedString {
           attribute DOMString baseVal;
  readonly attribute DOMString animVal;
};

The baseVal and animVal IDL attributes represent the current non-animated value of the reflected attribute. On getting baseVal or animVal, the following steps are run:

  1. If the reflected attribute is not present, then:
    1. If the SVGAnimatedString object is defined to additionally reflect a second, deprecated attribute, and that attribute is present, then return its value.
    2. Otherwise, if the reflected attribute has an initial value, then return it.
    3. Otherwise, return the empty string.
  2. Otherwise, the reflected attribute is present. Return its value.

For the href member on the SVGURIReference interface, this will result in the deprecated xlink:href attribute being returned if it is present and the ‘href’ attribute is not, and in the ‘href’ attribute being returned in all other cases.

On setting baseVal, the following steps are run:

  1. If the reflected attribute is not present, the SVGAnimatedString object is defined to additionally reflect a second, deprecated attribute, and that deprecated attribute is present, then set that deprecated attribute to the specified value.
  2. Otherwise, set the reflected attribute to the specified value.

For the href member on the SVGURIReference interface, this will result in the deprecated xlink:href attribute being set if it is present and the ‘href’ attribute is not, and in the ‘href’ attribute being set in all other cases.

4.6.8. Interface SVGAnimatedRect

An SVGAnimatedRect object is used to reflect an animatable attribute that takes a rectangle value as specified by an x, y, width and height.

In this specification the only attribute to be reflected as an SVGAnimatedRect is viewBox.

interface SVGAnimatedRect {
  [SameObject] readonly attribute DOMRect baseVal;
  [SameObject] readonly attribute DOMRectReadOnly animVal;
};

The baseVal and animVal IDL attributes represent the current non-animated rectangle value of the reflected attribute. On getting baseVal or animVal, a DOMRect object is returned.

Upon creation of the baseVal or animVal DOMRect objects, and afterwards whenever the reflected content attribute is added, removed, or changed, the following steps are run:

  1. Let value be the value of the reflected attribute (using the attribute's initial value if it is not present or invalid).
  2. Let x, y, width and height be those corresponding components of value.
  3. Set the DOMRect object's x coordinate, y coordinate, width and height to x, y, width and height, respectively.

Whenever the x coordinate, y coordinate, width or height property of the baseVal or animVal DOMRect object changes, except as part of the previous algorithm that reflects the value of the content attribute into the DOMRect, the reflected content attribute must be reserialized.

4.6.9. Interface SVGAnimatedNumberList

An SVGAnimatedNumberList object is used to reflect an animatable attribute that takes a list of <number> values.

interface SVGAnimatedNumberList {
  [SameObject] readonly attribute SVGNumberList baseVal;
  [SameObject] readonly attribute SVGNumberList animVal;
};

The baseVal and animVal IDL attributes represent the current non-animated value of the reflected attribute. On getting baseVal or animVal, an SVGNumberList object is returned that reflects the base value of the reflected attribute.

4.6.10. Interface SVGAnimatedLengthList

An SVGAnimatedLengthList object is used to reflect an animatable attribute that takes a list of <length>, <percentage> or <number> values.

interface SVGAnimatedLengthList {
  [SameObject] readonly attribute SVGLengthList baseVal;
  [SameObject] readonly attribute SVGLengthList animVal;
};

The baseVal or animVal IDL attributes represent the current non-animated value of the reflected attribute. On getting baseVal or animVal, an SVGLengthList object is returned that reflects the base value of the reflected attribute.

4.6.11. Interface SVGStringList

The SVGStringList interface is a list interface whose elements are DOMString values. An SVGStringList object represents a list of strings.

interface SVGStringList {

  readonly attribute unsigned long length;
  readonly attribute unsigned long numberOfItems;

  void clear();
  DOMString initialize(DOMString newItem);
  getter DOMString getItem(unsigned long index);
  DOMString insertItemBefore(DOMString newItem, unsigned long index);
  DOMString replaceItem(DOMString newItem, unsigned long index);
  DOMString removeItem(unsigned long index);
  DOMString appendItem(DOMString newItem);
  setter void (unsigned long index, DOMString newItem);
};

The behavior of all of the interface members of SVGStringList are defined in the List interfaces section above.

4.7. Other DOM interfaces

4.7.1. Interface SVGUnitTypes

The SVGUnitTypes interface defines a commonly used set of constants used for reflecting gradientUnits, patternContentUnits and other similar attributes. It is mixed in to other interfaces for elements that support such attributes.

[NoInterfaceObject]
interface SVGUnitTypes {
  // Unit Types
  const unsigned short SVG_UNIT_TYPE_UNKNOWN = 0;
  const unsigned short SVG_UNIT_TYPE_USERSPACEONUSE = 1;
  const unsigned short SVG_UNIT_TYPE_OBJECTBOUNDINGBOX = 2;
};

The unit type constants defined on SVGUnitTypes have the following meanings:

ConstantMeaning
SVG_UNIT_TYPE_USERSPACEONUSECorresponds to the 'userSpaceOnUse' attribute value.
SVG_UNIT_TYPE_OBJECTBOUNDINGBOXCorresponds to the 'objectBoundingBox' attribute value.
SVG_UNIT_TYPE_UNKNOWNSome other type of value.

4.7.2. Interface SVGTests

The SVGTests interface is used to reflect conditional processing attributes, and is mixed in to other interfaces for elements that support these attributes.

[NoInterfaceObject]
interface SVGTests {
  [SameObject] readonly attribute SVGStringList requiredExtensions;
  [SameObject] readonly attribute SVGStringList systemLanguage;
};

The requiredExtensions IDL attribute reflects the requiredExtensions content attribute.

The systemLanguage IDL attribute reflects the systemLanguage content attribute.

4.7.3. Interface SVGFitToViewBox

The SVGFitToViewBox interface is used to reflect the viewBox and preserveAspectRatio attributes, and is mixed in to other interfaces for elements that support these two attributes.

[NoInterfaceObject]
interface SVGFitToViewBox {
  [SameObject] readonly attribute SVGAnimatedRect viewBox;
  [SameObject] readonly attribute SVGAnimatedPreserveAspectRatio preserveAspectRatio;
};

The viewBox IDL attribute reflects the viewBox content attribute.

The preserveAspectRatio IDL attribute reflects the preserveAspectRatio content attribute.

4.7.4. Interface SVGZoomAndPan

The SVGZoomAndPan interface is used to reflect the zoomAndPan attribute, and is mixed in to other interfaces for elements that support this attribute.

[NoInterfaceObject]
interface SVGZoomAndPan {

  // Zoom and Pan Types
  const unsigned short SVG_ZOOMANDPAN_UNKNOWN = 0;
  const unsigned short SVG_ZOOMANDPAN_DISABLE = 1;
  const unsigned short SVG_ZOOMANDPAN_MAGNIFY = 2;

  attribute unsigned short zoomAndPan;
};

The zoom and pan type constants defined on SVGZoomAndPan have the following meanings:

ConstantMeaning
SVG_ZOOMANDPAN_DISABLECorresponds to the 'disable' attribute value.
SVG_ZOOMANDPAN_MAGNIFYCorresponds to the 'magnify' attribute value.
SVG_ZOOMANDPAN_UNKNOWNSome other type of value.

The zoomAndPan IDL attribute represents the value of the zoomAndPan attribute. On getting zoomAndPan, the following steps are run:

  1. Let value be the current value of the zoomAndPan attribute (using the attribute's initial value if it is not present or invalid).
  2. Return the corresponding constant in the zoom and pan type constant table above for value.

On setting zoomAndPan, the following steps are run:

  1. Let value be the value being assigned to a zoomAndPan.
  2. If value is SVG_ZOOMANDPAN_UNKNOWN or does not correspond to an entry in the zoom and pan type constant table above, then return.
  3. Set the zoomAndPan attribute to the keyword value in the zoom and pan type constant table above that corresponds to value.

4.7.5. Interface SVGURIReference

The SVGURIReference interface is used to reflect the ‘href’ attribute and the deprecated xlink:href attribute.

[NoInterfaceObject]
interface SVGURIReference {
  [SameObject] readonly attribute SVGAnimatedString href;
};

The href IDL attribute represents the value of the ‘href’ attribute, and, on elements that are defined to support it, the deprecated xlink:href attribute. On getting href, an SVGAnimatedString object is returned that:

The SVGAnimatedString interface is defined to reflect, through its baseVal and animVal members, the deprecated xlink:href attribute, if that attribute is present and the ‘href’ is not, and to reflect the ‘href’ attribute in all other circumstances. Animation elements treat attributeName='xlink:href' as being an alias for targetting the ‘href’ attribute.


Chapter 5: Document Structure

5.1. Defining an SVG document fragment: the ‘svg’ element

5.1.1. Overview

An SVG document fragment consists of any number of SVG elements contained within an svg element.

An SVG document fragment can range from an empty fragment (i.e., no content inside of the svg element), to a very simple SVG document fragment containing a single SVG graphics element such as a rect, to a complex, deeply nested collection of container elements and graphics elements.

An SVG document fragment can stand by itself as a self-contained file or resource, in which case the SVG document fragment is an SVG document, or it can be embedded inline as a fragment within a parent HTML or XML document.

The following example shows simple SVG content embedded inline as a fragment within a parent XML document. Note the use of XML namespaces to indicate that the svg and ellipse elements belong to the SVG namespace:

<?xml version="1.0" standalone="yes"?>
<parent xmlns="http://example.org"
        xmlns:svg="http://www.w3.org/2000/svg">
   <!-- parent contents here -->
   <svg:svg width="4cm" height="8cm">
      <svg:ellipse cx="2cm" cy="4cm" rx="2cm" ry="1cm" />
   </svg:svg>
   <!-- ... -->
</parent>

This example shows a slightly more complex (i.e., it contains multiple rectangles) stand-alone, self-contained SVG document:

<?xml version="1.0" standalone="no"?>
<svg width="5cm" height="4cm" version="1.1"
     xmlns="http://www.w3.org/2000/svg">
  <desc>Four separate rectangles
  </desc>
    <rect x="0.5cm" y="0.5cm" width="2cm" height="1cm"/>
    <rect x="0.5cm" y="2cm" width="1cm" height="1.5cm"/>
    <rect x="3cm" y="0.5cm" width="1.5cm" height="2cm"/>
    <rect x="3.5cm" y="3cm" width="1cm" height="0.5cm"/>

  <!-- Show outline of viewport using 'rect' element -->
  <rect x=".01cm" y=".01cm" width="4.98cm" height="3.98cm"
        fill="none" stroke="blue" stroke-width=".02cm" />

</svg>

svg elements can appear in the middle of SVG content. This is the mechanism by which SVG document fragments can be embedded within other SVG document fragments.

Another use for svg elements within the middle of SVG content is to establish a new SVG viewport. (See Establishing a new SVG viewport.)

5.1.2. Namespace

When SVG is parsed as a XML, for compliance with the Namespaces in XML Recommendation [xml-names], an SVG namespace declaration must be provided so that all SVG elements are identified as belonging to the SVG namespace.

When using the HTML syntax, the namespace is provided automatically by the HTML parser.

<html>
<svg viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="50" fill="green">
</svg>
</html>

As the example shows there's no need to have an ‘xmlns’ attribute declaring that the element is in the SVG namespace when using the HTML parser. The HTML parser will automatically create the SVG elements in the proper namespace.

This section should talk about how a document's behavior is defined in terms of the DOM, and also explain how the HTML parser can create SVG fragments.

The SVG 2 namespace is http://www.w3.org/2000/svg, which is the same as for earlier versions of SVG.

The following are possible ways to provide a namespace declaration when SVG is parsed as XML. An ‘xmlns’ attribute without a namespace prefix could be specified on an svg element, which means that SVG is the default namespace for all elements within the scope of the element with the ‘xmlns’ attribute:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
  <rect x="10" y="10" width="80" height="80" fill="green" />
</svg>

If a namespace prefix is specified on the ‘xmlns’ attribute (e.g., xmlns:svg="http://www.w3.org/2000/svg"), then the corresponding namespace is not the default namespace, so an explicit namespace prefix must be assigned to the elements:

<svg:svg xmlns:svg="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
  <svg:rect x="10" y="10" width="80" height="80" fill="green" />
</svg:svg>

Namespace prefixes can be specified on ancestor elements (illustrated in the above example). For more information, refer to the Namespaces in XML Recommendation [xml-names].

5.1.3. Definitions

structural element
The structural elements are those which define the primary structure of an SVG document. Specifically, the following elements are structural elements: defs, g, svg, symbol and use.
structurally external element
Elements that define its structure by reference to an external resource. Specifically, the following elements are structurally external elements when they have an ‘href’ attribute: audio, foreignObject, iframe, image, script, use and video.
current SVG document fragment
The document sub-tree which starts with the outermost ancestor svg element of a given SVG element, with the requirement that all container elements between the outermost svg and the given element are all elements in the SVG namespace.
outermost svg element
The furthest svg ancestor element that remains in the current SVG document fragment.
SVG document fragment
A document sub-tree which starts with an svg element which is either the root element of the document or whose parent element is not in the SVG namespace. An SVG document fragment can consist of a stand-alone SVG document, or a fragment of a parent document enclosed by an svg element. Howevere, an svg element that is a direct child of another SVG-namespaced element is not the root of an SVG document fragment.
SVG elements
Any element in the SVG namespace.
graphics element
One of the element types that can cause graphics to be drawn onto the target canvas. Specifically: audio, canvas, circle, ellipse, foreignObject, iframe, image, line, mesh, path, polygon, polyline, rect, text, textPath, tspan and video.
graphics referencing element
A graphics element which uses a reference to a different document or element as the source of its graphical content. Specifically: audio, iframe, image, mesh, use and video.

5.1.4. The ‘svg’ element

SVG 2 Requirement: Support transforming svg elements.
Resolution: We will allow ‘transform’ on ‘svg’ in SVG 2.
Purpose: To allow transforms on nested svg elements, in line with author expectations.
Owner: Dirk (no action)
Status: Done
svg
Categories:
Container element, renderable element, structural element
Content model:
Any number of the following elements, in any order:a, audio, canvas, clipPath, cursor, filter, foreignObject, iframe, image, marker, mask, script, style, switch, text, video, view
Attributes:
Geometry properties:
DOM Interfaces:

The x and y attributes specify the top-left corner of the rectangular region into which an embedded svg element is placed. On an outermost svg element, these attributes have no effect.

For outermost svg elements, the width and height attributes specify the intrinsic size of the SVG document fragment. For embedded svg elements, they specify the size of the rectangular region into which the svg element is placed. In either case, a computed style of auto is treated equivalent to 100%.

Attribute definitions:

Name Value Initial value Animatable
zoomAndPan disable | magnify magnify no

Specifies whether the user agent should supply a means to zoom and pan the SVG content. See the definition of zoomAndPan for details.

If an SVG document is likely to be referenced as a component of another document, the author will often want to include a viewBox attribute on the outermost svg element of the referenced document. This attribute provides a convenient way to design SVG documents to scale-to-fit into an arbitrary SVG viewport.

The svg element exposes as event handler content attributes a number of the event handlers of the Window object. It also mirrors their event handler IDL attributes.

The onblur, onerror, onfocus, onload, and onscroll event handlers of the Window object, exposed on the svg element, replace the generic event handlers with the same names normally supported by SVG elements.

5.2. Grouping: the ‘g’ element

5.2.1. Overview

container element
An element which can have graphics elements and other container elements as child elements. Specifically: a, clipPath, defs, g, marker, mask, pattern, svg, switch, symbol and unknown.

The g element is a container element for grouping together related graphics elements.

A group of elements, as well as individual objects, can be given a name using the id attribute. Named groups are needed for several purposes such as animation and re-usable objects.

An example:

<?xml version="1.0" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg"
     version="1.1" width="5cm" height="5cm">
  <desc>Two groups, each of two rectangles</desc>
  <g id="group1" fill="red">
    <rect x="1cm" y="1cm" width="1cm" height="1cm"/>
    <rect x="3cm" y="1cm" width="1cm" height="1cm"/>
  </g>
  <g id="group2" fill="blue">
    <rect x="1cm" y="3cm" width="1cm" height="1cm"/>
    <rect x="3cm" y="3cm" width="1cm" height="1cm"/>
  </g>

  <!-- Show outline of viewport using 'rect' element -->
  <rect x=".01cm" y=".01cm" width="4.98cm" height="4.98cm"
        fill="none" stroke="blue" stroke-width=".02cm"/>
</svg>

View this example as SVG (SVG-enabled browsers only)

A g element can contain other g elements nested within it, to an arbitrary depth.

5.2.2. The ‘g’ element

g
Categories:
Container element, renderable element, structural element
Content model:
Any number of the following elements, in any order:a, audio, canvas, clipPath, cursor, filter, foreignObject, iframe, image, marker, mask, script, style, switch, text, video, view
Attributes:
DOM Interfaces:

5.3. Unknown elements

SVG 2 Requirement: Have unknown elements treated as g for the purpose of rendering.
Resolution:
Purpose: To allow fallbacks without the use of switch, and to align with the behavior of unknown elements in HTML.
Owner: Nobody (no action)
Status:
unknown
Categories:
Container element, renderable element
Content model:
Any elements or character data.
Attributes:
DOM Interfaces:

Treating unknown elements as a generic container element, resulting in the rendering of their child trees, and assigning the SVGUnknownElement interface to unknown elements are both at risk, with no known implementations.

Unknown elements are all elements that are in the SVG namespace that are not defined by this specification or any SVG module. The SVGUnknownElement interface must be used for unknown elements.

Unknown elements in the SVG namespace are renderable elements and container elements. They must render as if the unknown element were replaced with a g element or tspan, according to context. Any global attribute or property that is valid on any SVG graphics element is also valid on unknown elements, and must be processed as normal. This includes conditional processing attributes, ARIA attributes, data attributes, and the lang, id, class, tabindex and style. Styles specified on unknown elements must be inherited by their child elements according to the normal rules for inheritance for each style property.

Known and unknown elements in other namespaces that occur as a child of any SVG element except foreignObject, must not render unless explicitly stated otherwise in this specification.

Known elements in the SVG namespace that occur in places where SVG's content model doesn't explicitly allow it must not render unless explicitly stated otherwise in this specification.

Consequently, in the following example:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 700 200">
  <rect x=".1" y=".1" width="699.8" height="199.8"
        fill="none" stroke="blue" stroke-width=".2" />
  <mysteryElement>
    <path d="M0 0h600v200h-600z" fill="darkkhaki"/>
  </mysteryElement>
  <hideElement xmlns="http://www.example.com/invisibleML">
    nothing to see here
    <path d="M0 0h300v100h-300z" fill="whitesmoke"/>
  </hideElement>
  <text y="2em" font-size="20"><text>This text must not be visible</text></text>
  <linearGradient>
    <gradientExtension>
      <path d="M300 0h100v200h-100z" fill="fuchsia"/>
    </gradientExtension>
  </linearGradient>
  <div xmlns="http://www.w3.org/1999/xhtml">This must not be visible</div>
</svg>

View this example as SVG (SVG-enabled browsers only)

5.4. Defining content for reuse, and the ‘defs’ element

5.4.1. Overview

SVG allows graphical objects to be defined for later reuse. To do this, it makes extensive use of URL references [rfc3987] to these other objects. For example, to fill a rectangle with a linear gradient, you first define a linearGradient element and give it an ID, as in:

<linearGradient id="MyGradient">...</linearGradient>

You then reference the linear gradient as the value of the fill property for the rectangle, as in:

<rect style="fill:url(#MyGradient)"/>

Some types of element, such as gradients, will not by themselves produce a graphical result. They can therefore be placed anywhere convenient. However, sometimes it is desired to define a graphical object and prevent it from being directly rendered. it is only there to be referenced elsewhere. To do this, and to allow convenient grouping defined content, SVG provides the ‘defs’ element.

It is recommended that, where possible, referenced elements be defined prior to the elements that use them, in document order. Collecting all referenced elements inside of a single defs element near the top of the file can make the markup easier to read and understand.

5.4.2. The ‘defs’ element

defs
Categories:
Container element, never-rendered element, structural element
Content model:
Any number of the following elements, in any order:a, audio, canvas, clipPath, cursor, filter, foreignObject, iframe, image, marker, mask, script, style, switch, text, video, view
Attributes:
DOM Interfaces:

The defs element is a container element for referenced elements. For understandability and accessibility reasons, it is recommended that, whenever possible, referenced elements be defined inside of a defs.

The content model for defs is the same as for the g element; thus, any element that can be a child of a g can also be a child of a defs, and vice versa.

Elements that are descendants of a defs are not rendered directly; the display value for the defs element must always be set to none by the user agent style sheet, and this declaration must have importance over any other CSS rule or presentation attribute. Note, however, that the descendants of a defs are always present in the source tree and thus can always be referenced by other elements; thus, the value of the display property on the defs element does not prevent those elements from being referenced by other elements.

5.5. The ‘symbol’ element

The symbol element is used to define graphical templates which can be instantiated by a use element but which are not rendered directly.

A symbol establishes a nested coordinate system for the graphics it contains. When a symbol is instantiated as the referenced element of a use element, it is therefore rendered very similarly to a nested svg element.

symbol
Categories:
Container element, structural element
Content model:
Any number of the following elements, in any order:a, audio, canvas, clipPath, cursor, filter, foreignObject, iframe, image, marker, mask, script, style, switch, text, video, view
Attributes:
Geometry properties:
DOM Interfaces:

The x, y, width, and height geometry properties have the same effect as on an svg element, when the symbol is instantiated by a use element. In particular, if width and height compute to auto (and are not over-ridden by values on the instantiating use element), then they will be treated as a value of 100%.

New in SVG 2. Allowing geometry properties to be specified on a symbol provides a more consistent rendering model, and allows authors to set a default size for each symbol (which may still be over-ridden by attributes on the use element).

5.5.1. Attributes

Name Value Initial value Animatable
refX <length> | left | center | right (none) yes
refY <length> | top | center | bottom (none) yes

New in SVG 2. Added to make it easier to align symbols to a particular point, as is often done in maps. Similar to the matching attributes on marker.

Add refX/refY to symbol element. Resolved at Leipzig F2F. Status: Done.

We will add top/center/bottom, left/center/right keywords to refX/refY on marker/symbol. Resolved at London F2F. Values inspired by 'background-position'. Status: Done.

The refX and refY attributes define the reference point of the symbol which is to be placed exactly at the symbol's x,y positioning coordinate, as defined by the cumulative effect of the x and y properties and any transformations on the symbol and its host use element.

Keyword values have the same meaning as for the refX and refY attributes on the marker element, resolving to 0%, 50%, or 100% in the applicable direction.

Unlike other positioning attributes, refX and refY are interpreted as being in the coordinate system of the symbol contents, after application of the viewBox and preserveAspectRatio attributes. If one or both of the attributes is not specified, no adjustment is made in the corresponding dimension, and the top or left side of the symbol's rectangular viewport region (regardless of the viewBox coordinates) is positioned at the x,y point.

For backwards compatibility, the behavior when refX and refY are not specified on a symbol is different from when they are specified with a value of 0, and therefore different from the behavior when equivalent attributes are not specified on a marker.

5.5.2. Notes on symbols

The use of symbol elements for graphics that are used multiple times in the same document adds structure and semantics. Closely related to the symbol element are the marker and pattern elements; all three define a container of graphical content that can be rendered repeatedly at various positions and scales in the SVG. However, while re-used graphics in a pattern and marker provide a graphical effect on another element, the content in a symbol will be embedded as fully interactive content, within a use-element shadow tree.

The user agent style sheet sets the overflow property for symbol elements to hidden, which causes a rectangular clipping path to be created at the bounds of symbol's SVG viewport. Unless the overflow property is overridden, any graphics within the symbol which goes outside of the symbol's SVG viewport will be clipped.

symbol elements must never be rendered directly; their only usage is as something that can be referenced using the use element. The user agent must set the display property on the symbol element to none, as part of the user agent style sheet, and this declaration must have importance over any other CSS rule or presentation attribute.

The generated instance of a symbol that is the direct referenced element of a use element must always have a computed value of inline for the display property. In other words, it must be rendered whenever the host use element is rendered. The user agent style sheet again defines this declaration to have importance over any other CSS rule or presentation attribute. Any other symbol that is cloned to create an element instance within the use-element shadow tree behaves as a symbol definition, and must not be rendered.

5.6. The ‘use’ element

SVG 2 Requirement: Allow use to reference an external document's root element by omitting the fragment.
Resolution: We will relax referencing requirements to particular elements to allow dropping fragments to mean referencing root element, where it makes sense, such as with use, in SVG 2.
Purpose: To avoid requiring authors to modify the referenced document to add an ID to the root element.
Owner: Cameron (ACTION-3417)
Status: Done
use
Categories:
Graphics referencing element, renderable element, structural element, structurally external element
Content model:
Any number of the following elements, in any order:clipPath, mask, script, style
Attributes:
Geometry properties:
DOM Interfaces:

The use element references another element, a copy of which is rendered in place of the use in the document. The referenced element may be a container element, in which case a copy of the complete SVG document subtree rooted at that element is used.

The cloned content inherits styles from the use element and can be the target of user events. However, these cloned element instances remain linked to the referenced source and reflect DOM mutations in the original. In addition, all style rules that apply in the scope of the referenced element also apply in the scope of the cloned shadow tree.

The x, y, width and height geometric properties specify the positioning of the referenced element. The width and height attributes only have an effect if the referenced element defines a viewport (i.e., if it is a svg or symbol); if so, a value other than auto for the use element overrides the value of the corresponding geometric property on that element.

A negative value for width or height must be treated as an illegal value. If width or height is zero, and the properties have an effect on the referenced element, then rendering of that element will be disabled.

The x and y properties affect the user coordinate system for the element. See the Layout section for implementation details.

Name Value Initial value Animatable
href URL [URL] (none) yes

An URL reference to the element/fragment within an SVG document to be cloned for rendering.

The use element can reference an entire SVG document by specifying an href value without a fragment. Such references are taken to be referring to the root element of the referenced document.

Refer to the common handling defined for URL reference attributes and deprecated XLink attributes.

New in SVG 2. An href without a fragment allows an entire SVG document to be referenced without having to ensure that it has an ID on its root element.

User agents may restrict external resource documents for security reasons. In particular, this specification does not allow cross-origin resource requests in use. A future version of this or another specification may provide a method of securely enabling cross-origin re-use of assets.

When the href attribute is set (or, in the absence of an href attribute, an xlink:href attribute), the user agent must process the URL. The target element that results from URL processing is the referenced element of the use.

If the referenced element that results from resolving the URL is neither an SVG element nor an HTML-namespaced element that may be included as a child of an SVG container element, then the reference is invalid and the use element is in error.

If the referenced element is a (shadow-including) ancestor of the use element, then this is an invalid circular reference and the use element is in error.

Otherwise, the user agent must generate a shadow tree of re-used graphics to render as the contents of the use element, as described in the next section, The use-element shadow tree.

A use that has an unresolved or invalid URL reference is not rendered. For the purpose of bounding box calculations, it is equivalent to an empty container element.

5.6.1. The use-element shadow tree

The re-used graphics generated by a use element are defined in terms of a shadow tree. In terms of interactivity and style inheritance, they are therefore quite different from other types of re-used graphics in SVG, such as pattern and marker content.

Elements in the shadow tree are rendered as if the use element was a container and they were its children. However, the SVG Document Object Model (DOM) only contains the use element and its attributes. The SVG DOM does not include the element instances as children of the use element.

User agents that support scripting and the document object model must implement the use-element shadow tree as described in this section and in conformance with the Shadow DOM specification [SHADOWDOM], or its future replacement. In contrast, user agents that do not support the dynamic interactive processing mode may not need to implement all the details of the shadow DOM. However, all user agents must ensure that the layout and style inheritance for the re-used graphics, and any multimedia and declarative animations if applicable, are rendered in the same way as if the shadow DOM was implemented.

The following definitions apply when discussing use elements and their shadow trees:

referenced element
The element specified by the href (or xlink:href) attribute on the use element, or the root element of a document referenced by that attribute if the URL provided does not include a target fragment that links to a specific element id.
referenced document subtree
referenced graphics
The referenced element, and all of its descendent nodes.
shadow root
A ShadowRoot object, a type of DocumentFragment node which is associated with a host Element, and which contains the content that will be used to render that host. A shadow root should be implemented in conformance with the Shadow DOM specification [SHADOWDOM], or its future replacement.
shadow host
host
An element that has an associated shadow root; usage is consistent the definition of host in the DOM standard.
shadow tree
A node tree whose root is a shadow root; usage is consistent the definition of shadow tree in the DOM standard.
use-element shadow tree
A shadow tree whose host is a use element, which contains element instances generated by cloning the referenced graphics.
element instance
instance
An element in the use-element shadow tree, which is generated by cloning a corresponding element in the referenced document subtree.
instance root
The element instance for the referenced element; it is always a direct child of the use element's shadow root.
corresponding element
For each element instance, the element in the referenced document subtree from which it is cloned.
corresponding use element
For each element instance, the use element which causes it to be rendered in the document. This is the instance's shadow root's host use element if that element is not itself an element instance within a use element shadow tree, or is that element's corresponding use element otherwise, recursively exiting shadow trees as many times as necessary to reach a use element that was not itself generated as part of the shadow tree of another use element.

When the user agent successfully resolves a use element to identify a referenced element, the user agent must create a use-element shadow tree whose host is the use element itself. The shadow tree must be created even if the use element is not rendered because it is a descendent of a never-rendered element, because of conditional processing, or because of the display property being set to none on it or an ancestor element.

Each node in the shadow tree is an instance of a corresponding node from the referenced document subtree. The shadow nodes all descend from the instance root, which is the instance of the referenced element, and which itself is a direct child of the shadow root node.

The shadow tree is open (inspectable by script), but read-only. Any attempt to directly modify the elements, attributes, and other nodes in the shadow tree must throw a NoModificationAllowedError.

Within a use-element shadow tree, script elements are inert (do not execute); audio and video elements are subject to the limitations specified in the Multimedia section.

Previous versions of SVG restricted the contents of the shadow tree to SVG graphics elements. This specification allows any valid SVG document subtree to be cloned. Cloning non-graphical content, however, will not usually have any visible effect.

If the referenced element is in an external file, then all URL references in attributes and style properties must be made absolute as described in Generating the absolute URL, before copying the value to the element instances. The shadow tree itself uses the same document base URL as the document that includes it.

The user agent must ensure that all mutations to the referenced document subtree are reflected in the shadow tree. This includes changes to elements, attributes, and text and other nodes. In addition, changes to the stylesheets in effect for the referenced graphics must be reflected in changes to the stylesheets in the shadow tree's scope, as described futher in the section on style inheritance.

If either the use element or the referenced element is altered in a way that causes the use element's URL reference to become unresolved again, then the entire shadow tree for that use element is discarded.

When a use references another element which is another use or whose content contains a use element, then the shadow DOM cloning approach described above is recursive. However, a set of references that directly or indirectly reference a element to create a circular dependency is an invalid circular reference. The use element or element instance whose shadow tree would create the circular reference is in error and must not be rendered by the user agent.

5.6.2. Layout of re-used graphics

The value of the x, y, width and height properties on a use element are used to position the re-used graphics and to set the viewport size if the referenced element defines a nested viewport. The effect of these properties on a use element is notably different from their effect on a graphics element, or from their effect in CSS box layout.

The x and y properties define an additional transformation (translate(x,y), where x and y represent the computed value of the corresponding property) to be applied to the use element, after any transformations specified with other properties (i.e., appended to the right-side of the transformation list).

For historical reasons, the supplemental transformation is applied to the use element itself, rather than solely to the re-used content in the shadow tree. This affects the coordinate system used for any masks, clipping paths, or filters applied to the use element and calculated in userSpaceOnUse units.

To apply userSpaceOnUse graphical effects in an un-transformed coordinate space, while also using the x and y to position the graphics, authors can nest the use element inside a g, and apply the graphical effects to the g element.

The width and height properties on the use element override the values for the corresponding properties on a referenced svg or symbol element when determining the used value for that property on the instance root element. However, if the computed value for the property on the use element is auto, then the property is computed as normal for the element instance.

These properties can therefore be used to scale a graphic that defines its own coordinate system, each time it is re-used. Because auto is the initial value, if dimensions are not explicitly set on the use element, the values set on the svg or symbol will be used as defaults.

The width and height properties on the use element have no effect if the referenced element does not establish a new viewport. In particular, the use element does not itself establish a new viewport, and therefore does not affect the interpretation of percentages in the re-used graphics.

In all other ways, rendering and layout of elements within the use-element shadow tree occurs as if the use element was a container for its shadow content. In particular, unless elements within the shadow tree establish a new viewport, they must be drawn in the coordinate system in which the use element is defined (including any cumulative transformations). This affects the interpretation of percentage lengths, and also graphical effects with userSpaceOnUse units.

5.6.3. Style Scoping and Inheritance

The use-element shadow tree, like other shadow trees, exhibits style encapsulation, as defined in the CSS Scoping module [css-scoping-1]. This means that elements in the shadow tree inherit styles from its host use element, but that style rules defined in the outer document do not match the elements in the shadow tree. Instead, the shadow tree maintains its own list of stylesheets, whose CSS rules are matched against elements in the shadow tree.

Presentation attributes and the style attribute are cloned from the elements in the referenced graphics into the element instances in the same manner as other attributes.

When the referenced element is from the same document as the use element, the same document stylesheets will apply in both the original document and the shadow tree document fragment. Any changes to the stylesheets in the main document also affect the shadow tree; the StyleSheetList object accessed through the document and shadow root document fragment's styleSheets properties must be identical. If a style element is duplicated as part of the referenced document subtree, then the styleSheet property on the element instance points to the same object as for the corresponding element.

When the referenced element is from an external document, the stylesheet objects generated when processing that document apply to the shadow tree, and are read-only. All URL references in the stylesheet, including fragment-only references, must be made absolute, relative to the URL of the document that contains the referenced element. User agents may re-use the same stylesheet objects for any shadow trees that reference that same external document.

Style rules that are scoped to the shadow tree cannot normally affect any elements in the main document. Similarly, style rules in the main document can only affect the shadow tree elements by changing inherited values. However, CSS Scoping defines special selectors for styling the host element from within the shadow tree, or for adjusting styles within the shadow tree in response to changes in the host's context [css-scoping-1].

CSS media queries within a shadow tree's scope are evaluated using the same device features and dimensions as the corresponding "light" document (that is, the document that contains the corresponding use element for the shadow tree, after recursively exiting all nested shadow trees).

In most cases, the element instance in the shadow tree will match the same style rules as its corresponding element in the original document. However, if a CSS rule uses a complex selector to match an element based on its ancestors or siblings, and those ancestors or siblings are not cloned as part of the shadow tree, then that rule would no longer match the element instance. Similarly, child-indexed pseudo-classes such as nth-of-type and nth-child may apply to one element but not the other. This represents a change from how style cloning was defined in previous versions of SVG.

The following example demonstrates both the consistent and changed style-matching rules. The circle on the left is re-used to draw the circle on the right. The original circle has styles set in various ways:

In the SVG 1.1 style-cloning model, the specified style values would be cloned from the original element to the element instance. The re-used circle would have the same styles as the original, except that the fill value would be inherited from the use (orange) instead of from the g (blue).

In the shadow DOM model required by SVG 2, the styles for the re-used circle are calculated as follows:

The re-used circle therefore differs from the original in both fill color (because it inherits from a different element) and stroke color (because the complex selector no longer matches).

<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     width="200" height="100" viewBox="0 0 200 100">
  <title>Style inheritance and the use element</title>
  <desc>
    Two circles, one of which is a re-styled clone of the other.
    This file demonstrates one of the cases where 
    the shadow-DOM style matching rules in SVG 2
    have a different effect than the SVG 1.1 style cloning rules. 
    The original circle on the left
    should have blue fill 
    and green stroke.
    In a conforming SVG 1.1 user agent,
    the re-used circle on the right
    should have orange fill and green stroke.
    In a conforming SVG 2 user agent,
    the re-used circle should have orange fill and purple stroke.
    In all cases,
    the stroke should be partially transparent
    and 20 units wide, 
    relative to a total circle diameter of 100 units.
  </desc>
  <style type="text/css">
    circle          { stroke-opacity: 0.7; }
    .special circle { stroke: green; }
    use             { stroke: purple;
                      fill: orange; }
  </style>
  <g class="special" style="fill: blue">
     <circle id="c" cy="50" cx="50" r="40" 
             stroke-width="20" />
  </g>
  <use xlink:href="#c" x="100" />
</svg>
Example Use-changed-styles — A 'use' element copying a 'circle', with various style matching rules demonstrated

Example Use-changed-styles

View this example as SVG (SVG-enabled browsers only)

Previous versions of SVG were not clear about how dynamic pseudo-classes (such as :hover) should apply to element instances. The shadow tree model requires that all such pseudo-classes are matched independently to the element instance or to its corresponding element, depending on which element the user is interacting with.

Specifying 'visibility:hidden' on a use element does not guarantee that the referenced content will not be rendered. Unlike the display or the opacity properties, the visibility property does not appy directly to container elements, and therefore does not apply directly to the use element. Because visibility is normally inherited, hiding the use element will often hide the child content, but not necessarily. If any graphics elements in the shadow tree have 'visibility:visible' specified, then that element will be visible even if the use element specifies 'visibility:hidden'.

In the following example, key style rules are as follows:

.dark {
  visibility: hidden;
}
.eyes {
  visibility: visible;
}
svg:hover .dark, svg:focus .dark {
  visibility: visible;
}

The "dark" class is set on the group containing the use elements, so all parts of the re-used graphics inherit the hidden visibility setting, except for the subtrees with class "eyes", where it is reset to visible. Upon hovering or focusing the graphic, the hiding effect is removed.

Multiple use-copies of a creature-symbol on a black background; the use elements have visibility: hidden, but the creatures' eyes have visibility: visible.

Example Use-visibility-hidden, default styles

Multiple use-copies of a rabbit-symbol on a light green background; each rabbit has different=coloured fur, but the same pink noses and white fluffy tails.

Example Use-visibility-hidden, interactive styles

View this example as SVG

The example also demonstrates inheritance of other style properties (fill and stroke) specified on the use elements, and how these are also not used if any elements within the symbol specify explicit values (e.g., the pink noses and ears and the white tails).

5.6.4. Multimedia in use-element shadow trees

When a use-element shadow tree includes audio or video elements, the following behaviors must be enforced:

5.6.5. Animations in use-element shadow trees

The Web Animations API [web-animations-1] and the SVG Animations specification [svg-animation] define non-CSS ways to animate attributes and styles on targetted elements without directly manipulating DOM properties (see the Animation appendix for details). User agents that implement those features must ensure that all animations that apply to an element in a referenced document subtree also apply to instances of that element in a use-element shadow tree, as described in this section.

Scripted animations created by directly manipulating attributes on elements in the referenced graphics (including the style attribute or its IDL property) will be propagated to the element instances in the shadow tree in the same manner as any other DOM manipulations.

Animation effects applied using CSS will be duplicated along with other stylesheet rules, following the procedure specified in the Style Scoping and Inheritance section.

All animations within a use-element shadow tree operate in the same document timeline as for the corresponding use element, regardless of whether the referenced element is from the same or an external document.

For animation effects applied using a Web Animations API method [web-animations-1], if the target of the animation is a corresponding element to an element instance in a shadow tree, the user agent must construct a ShadowAnimation whose source is that Animation object and whose target is the element instance. If there are multiple instances of the element in different trees, then there will be multiple shadow animations, one for each.

The user agent must create such a ShadowAnimation for all Web Animations API animations in effect (including pending and frozen animations) at the time the shadow tree is generated, and for any new animations applied while the shadow tree exists. The user agent must not create ShadowAnimation objects for CSS animations or animation elements (as these are duplicated separately).

As part of the interface definition, a ShadowAnimation is read-only, and must reflect any changes to its sourceAnimation.

Any attempts to directly apply new animations to a target that is a read-only element instance (or pseudo-element) within a use-element shadow tree must throw a NoModificationAllowedError.

For each animation element [svg-animation] that targets an element in the referenced document subtree, the user agent must ensure that an equivalent animation element is in effect in the use-element shadow tree. If the animation element itself is part of the referenced document subtree, then this happens as a matter of course through the creation of an element instance for the animation element. Otherwise, the user agent must generate an element instance for the animation element that has the same effect as if it was a node in the shadow tree. The effective document order for these generated animation elements must be the same as the document order for their corresponding elements.

Each animation element or instance must only affect a target element in the same node tree (shadow or light), regardless of whether the targetting is implicit (the parent element) or explicit (a URL cross-reference to an element id). In this way, the one-to-one relationship between animation elements and target elements is preserved.

The id attribute is cloned, like any other attribute, from the corresponding element to the element instance; This does not conflict with the requirement for id to be unique, because the clone and the original are in distinct node trees.

All animation elements, in the document or in the shadow trees, which are timed to begin or end in response to an event on another element identified by its id attribute, must also begin or end when any instance of an element with that id receives the same event. This is consistent with how event listeners on a referenced element also listen to events on instances of that element, as described in the section on Event handling in use-element shadow trees. This behavior does not apply to animation begin or end times defined only by an event and not by an id (and therefore implicitly listening for the event on the target element); in that case, each animation element is only triggered by its own target.

At the time an instance of an animation element is generated within a shadow tree, if there is an active animation associated with the corresponding element (including a frozen animation), and the timing event that initiated that animation would also have initiated the instance if it existed, then the animation for the element instance must be initiated, with its begin time adjusted backwards in the document timeline to match the timing of the corresponding element.

In many cases, the requirements of this section mean that the element instance and its corresponding element will animate synchronously. This will be the case if the animation is purely time-based, or if it begins and ends in response to user interaction on an element referenced by its id. However, if the animation is triggered by a user interaction event on the targetted element (implicitly), then only the element or element instance that receives the interaction event will display the animation.

This is a change from previous versions of SVG, which required all animations on the corresponding element to be mirrored, regardless of user interaction, but which did not offer clear guidance for responding to user interactions with the element instances. The change ensures that interactive animations declared with animation elements behave in the same manner as interactive CSS styles and CSS animations.

In order to create animations that apply to all instances when any instance or the original element receives an event, specify the element id explicitly:


<set href="#target" begin="mouseover" ... />
  <!-- only affects the element that is moused over -->
  
<set href="#target" begin="target.mouseover" ... />
  <!-- affects all instances of the element with the id 'target',
          in all light and shadow node trees,
          when any of them are moused over -->
  

5.6.6. Event handling in use-element shadow trees

Element in a use-element shadow tree can both listen for and be the target of DOM events. Event retargetting provides encapsulation, so that the details of the shadow DOM structure are masked when an event bubbles out of the shadow tree and into the light.

Event retargeting is new in SVG 2. It provides consistency with the Shadow DOM specification, with existing implementations, and with the expectations of authors who are only concerned with elements in the main DOM.

Any event listeners defined on an element in the referenced graphics must also listen for the same event, at the same capture phase, on each instance of that element in a use-element shadow tree. This includes event listeners assigned using event attributes (which would be duplicated as with any other DOM attribute) and also event listeners assigned using the addEventListener method. The user agent must ensure that the list of event listeners for each element instance is synchronized to match its corresponding element. An event listener cannot be directly assigned to a read-only element instance in a use-element shadow tree. Any attempt to add an event listener to such an element must throw a NoModificationAllowedError.

Events in the use-element shadow tree are dispatched and bubble according to the shadow tree event path and event retargeting algorithm [SHADOWDOM].

In general, the event path for a use-element shadow tree is constructed from the ancestors of the event target element up to the shadow root, then the host use element and its event path through to the document window. This means that, in the capture phase, an event propagates from the window through the regular document tree to the use element and then to the shadow root object and down through the shadow tree (or recursively through multiple shadow trees) to the event target element. In the bubbling phase, the event passes in the opposite direction, from the shadow tree elements to the shadow root, then to the use element and its ancestors.

The event retargeting algorithm ensures that from the perspective of event listeners on the use element or its ancestors, all events targetted to element instances in the shadow tree instead have a target of the use element itself. If the event has both a target and a relatedTarget, and both of these properties would be retargeted to point to the same use element, then the event is not propagated at all outside of the shadow tree. This would occur, for example, if focus moved from one element inside the shadow tree to another. Certain other event types are constrained to not propagate outside of the shadow tree in which they were created.

In contrast, event listeners that process the event while it is propagating through the shadow tree (because the listener has been added to a corresponding element) will receive the event with its target pointing to a read-only element instance in the shadow tree. The correspondingElement and correspondingUseElement properties of that element instance can be used to connect it to the modifiable elements in the main DOM.

5.7. Conditional processing

5.7.1. Conditional processing overview

SVG contains a switch element along with attributes requiredExtensions and systemLanguage to provide an ability to specify alternate viewing depending on the capabilities of a given user agent or the user's language.

Attributes requiredExtensions and systemLanguage act as tests and evaluate to either true or false. The switch renders the first of its children for which all of these attributes test true. If the given attribute is not specified, then a true value is assumed.

When an element is excluded because of conditional processing, it is treated as if it had a used value of none for the display property. Similar to the display property, conditional processing attributes only affect the direct rendering of elements and do not prevent elements from being successfully referenced by other elements (such as via a use).

In consequence:

Previous versions of SVG included a third conditional processing attribute, requiredFeatures. This was intended to allow authors to provide fallback behavior for user agents that only implemented parts of the SVG specification. Unfortunately, poor specification and implementation of this attribute made it unreliable as a test of feature support.

5.7.2. Definitions

conditional processing attribute
A conditional processing attribute is one that controls whether or not the element on which it appears is processed. Most elements, but not all, may have conditional processing attributes specified on them. See Conditional processing for details. The conditional processing attributes defined in SVG 2 are requiredExtensions and systemLanguage.

5.7.3. The ‘switch’ element

switch
Categories:
Container element, renderable element
Content model:
Any number of the following elements, in any order:a, audio, canvas, foreignObject, g, iframe, image, svg, switch, text, use, video
Attributes:
DOM Interfaces:

The switch element evaluates the requiredExtensions and systemLanguage attributes on its direct child elements in order, and then processes and renders the first child for which these attributes evaluate to true. All others will be bypassed and therefore not rendered. If the child element is a container element such as a g, then the entire subtree is either processed/rendered or bypassed/not rendered.

In SVG, when evaluating the systemLanguage attribute, the order of evaluation of descendant elements of the switch element must be as if the 'allowReorder' attribute, defined in the SMIL specification [SMIL] always has a value of 'yes'.

Note that the values of properties display and visibility have no effect on switch element processing. In particular, setting display to none on a child of a switch element has no effect on true/false testing associated with switch element processing.

The switch element does not affect the processing of script and style elements.

For more information and an example, see Embedding foreign object types.

5.7.4. The ‘requiredExtensions’ attribute

The requiredExtensions attribute defines a list of required language extensions. Language extensions are capabilities within a user agent that go beyond the feature set defined in this specification. Each extension is identified by an URL reference.

Name Value Initial value Animatable
requiredExtensions set of space-separated tokens [HTML] (none) no

The value is a list of URL references which identify the required extensions, with the individual values separated by white space. Determines whether all of the named extensions are supported by the user agent. If all of the given extensions are supported, then the attribute evaluates to true; otherwise, the current element and its children are skipped and thus will not be rendered.

If a given URL reference contains white space within itself, that white space must be escaped.

If the attribute is not present, then it implicitly evaluates to "true". If a null string or empty string value is given to attribute requiredExtensions, the attribute evaluates to "false".

requiredExtensions is often used in conjunction with the switch element. If the requiredExtensions is used in other situations, then it represents a simple switch on the given element whether to render the element or not.

The URL names for the extension should include versioning information, such as "http://example.org/SVGExtensionXYZ/1.0", so that script writers can distinguish between different versions of a given extension.

5.7.5. The ‘systemLanguage’ attribute

Name Value Initial value Animatable
systemLanguage set of comma-separated tokens [HTML] (none) no

The value is a set of comma-separated tokens, each of which must be a Language-Tag value, as defined in BCP 47 [BCP47].

Evaluates to "true" if one of the languages indicated by user preferences exactly equals one of the languages given in the value of this parameter, or if one of the languages indicated by user preferences exactly equals a prefix of one of the languages given in the value of this parameter such that the first tag character following the prefix is "-".

Evaluates to "false" otherwise.

If the attribute is not present, then it implicitly evaluates to "true". If a null string or empty string value is given to attribute systemLanguage, the attribute evaluates to "false".

Note: This use of a prefix matching rule does not imply that language tags are assigned to languages in such a way that it is always true that if a user understands a language with a certain tag, then this user will also understand all languages with tags for which this tag is a prefix.

The prefix rule simply allows the use of prefix tags if this is the case.

Implementation note: When making the choice of linguistic preference available to the user, implementers should take into account the fact that users are not familiar with the details of language matching as described above, and should provide appropriate guidance. As an example, users may assume that on selecting "en-gb", they will be served any kind of English document if British English is not available. The user interface for setting user preferences should guide the user to add "en" to get the best matching behavior.

Multiple languages may be listed for content that is intended for multiple audiences. For example, content that is presented simultaneously in the original Maori and English versions, would call for:

<text systemLanguage="mi, en"><!-- content goes here --></text>

However, just because multiple languages are present within the object on which the systemLanguage test attribute is placed, this does not mean that it is intended for multiple linguistic audiences. An example would be a beginner's language primer, such as "A First Lesson in Latin," which is clearly intended to be used by an English-literate audience. In this case, the systemLanguage test attribute should only include "en".

Authoring note: Authors should realize that if several alternative language objects are enclosed in a switch, and none of them matches, this may lead to situations where no content is displayed. It is thus recommended to include a "catch-all" choice at the end of such a switch which is acceptable in all cases.

systemLanguage is often used in conjunction with the switch element. If the systemLanguage is used in other situations, then it represents a simple switch on the given element whether to render the element or not.

5.8. The ‘desc’ and ‘title’ elements

5.8.1. Definition

descriptive element
An element which provides supplementary descriptive information about its parent. Specifically, the following elements are descriptive elements: desc, metadata and title.

Multilingual descriptive text selection, based on the lang attribute, was added to allow internationalization of the desc and title elements.

New in SVG 2. Adding 'lang' resolved at Rigi Kaltbad face-to-face. Removed text that limited number of 'desc' and 'title' elements. Status: Done.

Any container element or graphics element in an SVG document can have zero or more desc and/or title elements as children, whose content is text. desc and title elements are not visually rendered as part of the graphics. The display value for the title and desc elements must always be set to none by the user agent style sheet, and this declaration must have importance over any other CSS rule or presentation attribute.

Multiple sibling desc or title elements must have different languages, as defined using a lang attribute (or xml:lang attribute) on the descriptive element or an ancestor. The user agent must select the element of each type whose language best matches language preferences set by the user. A descriptive element with an empty-string language tag (indicating no language, for example a text alternative consisting of emoji symbols) is a lowest-priority match for any user, ranked below all user-specified language preferences. If multiple equally valid matches exist, the first match should be used. If no match exists for either 'title' or 'desc', the first element of that type must be selected.

The following example shows alternative language titles on a re-used star icon, inline in an HTML document. The example assumes that the HTML document as a whole has a correctly-declared language of en (English without a specified country code).

<svg>
  <use href="#star">
    <title>Favourite</title>
    <title lang="en-us">Favorite</title>
    <title lang="nl">Favoriet</title>
    <title lang="">★</title>
  </use>
</svg>
  

The first title element inherits the language of the document (en); the others have explicitly-declared languages for each element. If the user's preferred language (out of those provided) is American English, the icon title is the American spelling "Favorite". If the user's preferred language is Dutch, the icon title is "Favoriet". If the user's preference list includes generic English ranked higher than Dutch, the title is "Favourite" with British spelling. If the user does not understand either Dutch or English, the title will be the star symbol character—which is not ideal (most screen readers will read it as a localized version of "black star"), but better than no text alternative at all.

Authors should be aware that SVG 1.1-supporting user agents that have not yet implemented multi-lingual descriptive text will normally select the first element of each type, regardless of user preferences. SVG 1.1 user agents may also fail to recognize a title element that is not the first child of its parent, or a desc element that has previous siblings that are not other descriptive elements.

The use of more than one title or desc element to provide localised information is at risk, with no known implementations.

User agents must make the text content of selected 'title' and 'desc' elements available to platform accessibility APIs as part of the name and description computation for the parent element, as defined in the SVG Accessibility API Mappings [SVG-AAM] specification.

Inclusion of any 'title' or 'desc' elements as a direct child of a rendered element indicates that the rendered element is of semantic importance in the graphic. Authors should not, and SVG generators must not, include empty 'title' or 'desc' elements with no text content or whitespace-only text content, as this will result in a nameless object being presented to assistive technology users.

If an individual graphic element has no meaning on its own, alternative text should instead be provided for the nearest container element that describes a meaningful object. Authors should use grouping (g) elements to structure their drawing elements into meaningful objects, and name those groups with title. Conversely, if a container object is used simply to apply styles or layout, and neither defines an object nor provides meaningful grouping structure, it does not need alternative text.

Descriptive text elements whose parent is not rendered may be used by authors or authoring tools as reference information; authors are warned that this data is not normally available to end users viewing the graphic through assistive technologies. Nonetheless, a non-rendered element may be referenced as part of the accessible name or description of a rendered element (as defined in SVG-AAM), and the recursive computation will use descriptive child elements of the referenced element.

Description and title elements may contain marked-up text from other namespaces, using standard XML mechanisms to indicate the namespace. However, authors should not rely on such markup to provide meaning to alternative text; only the plain text content is currently required to be exposed to assistive technologies.

The HTML parser treats all markup within title and desc the same way it treats markkup in an HTML fragment; most elements will be assigned to the HTML namespace.

User agents may use markup within title to influence the visual presentation of titles (such as tooltips), but are not required to do so.

title
Categories:
Descriptive element, never-rendered element
Content model:
Any elements or character data.
Attributes:
DOM Interfaces:

The title child element represents a short text alternative for the element.

On a link, this could be the title or a description of the target resource; on an image or drawing object, it could be a short description of the graphic; on interactive content, it could be a label for, or instructions for, use of the element; and so forth.

Authors should not provide redundant information in a title element if there is also a visible label for the drawing element (e.g., using a text element). Instead, the visual label should be associated with the drawing element using an aria-labelledby attribute.

Interactive user agents should make the plain text content of title elements available in response to user interaction, in a manner consistent with platform conventions; existing user agents commonly render title elements as a tooltip on hovering the parent element.

Authors should provide a title child element to the root svg element within a stand-alone SVG document. Since users often consult documents out of context, authors should provide context-rich titles. Thus, instead of a title such as "Introduction", which doesn't provide much contextual background, authors should supply a title such as "Introduction to Medieval Bee-Keeping" instead. For reasons of accessibility, user agents should always make the content of the ‘title’ child element to the root svg element available to users. However, this is typically done through other means than the tooltips used for nested SVG and graphics elements, e.g., by displaying in a browser tab.

desc
Categories:
Descriptive element, never-rendered element
Content model:
Any elements or character data.
Attributes:
DOM Interfaces:

The desc element represents more detailed textual information for the element such as a description. This is typically exposed to assistive technologies to provide more detailed information, such as a description of the visual appearance of a graphic or help to explain the functionality of a complex widget. It is not typically available to other users, so should not be used for essential instructions.

Authors may associate detailed information, including visible text, with part of the graphic using aria-describedby attribute (on the described element or a parent container), with the value being an ID reference to one or more SVG or HTML elements containing the description. The aria-describedby attribute takes precedence over the child desc when providing a description. If an element has both visible description and a child desc element providing supplementary information, authors should explicitly include the id of the element itself in its own aria-describedby list, in order to concatenate the two descriptions together.

5.9. The ‘metadata’ element

Metadata which is included with SVG content should be specified within metadata elements. The contents of the metadata should be elements from other XML namespaces, with these elements from these namespaces expressed in a manner conforming with the Namespaces in XML Recommendation [xml-names].

SVG 2 removes the recommendation to structure metadata elements in any particular way.

metadata
Categories:
Descriptive element, never-rendered element
Content model:
Any elements or character data.
Attributes:
DOM Interfaces:

Metadata content is not directly rendered; the display value for the metadata element must always be set to none by the user agent style sheet, and this declaration must have importance over any other CSS rule or presentation attribute.

Here is an example of how metadata can be included in an SVG document. The example uses the Dublin Core version 1.1 schema. (Other XML-compatible metadata languages, including ones not based on RDF, can be used also.)

<?xml version="1.0" standalone="yes"?>
<svg width="4in" height="3in"
    xmlns = 'http://www.w3.org/2000/svg'>
    <desc xmlns:myfoo="http://example.org/myfoo">
      <myfoo:title>This is a financial report</myfoo:title>
      <myfoo:descr>The global description uses markup from the
        <myfoo:emph>myfoo</myfoo:emph> namespace.</myfoo:descr>
      <myfoo:scene><myfoo:what>widget $growth</myfoo:what>
      <myfoo:contains>$three $graph-bar</myfoo:contains>
        <myfoo:when>1998 $through 2000</myfoo:when> </myfoo:scene>
   </desc>
    <metadata>
      <rdf:RDF
           xmlns:rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
           xmlns:rdfs = "http://www.w3.org/2000/01/rdf-schema#"
           xmlns:dc = "http://purl.org/dc/elements/1.1/" >
        <rdf:Description about="http://example.org/myfoo"
             dc:title="MyFoo Financial Report"
             dc:description="$three $bar $thousands $dollars $from 1998 $through 2000"
             dc:publisher="Example Organization"
             dc:date="2000-04-11"
             dc:format="image/svg+xml"
             dc:language="en" >
          <dc:creator>
            <rdf:Bag>
              <rdf:li>Irving Bird</rdf:li>
              <rdf:li>Mary Lambert</rdf:li>
            </rdf:Bag>
          </dc:creator>
        </rdf:Description>
      </rdf:RDF>
    </metadata>
</svg>

5.10. HTML metadata elements

For user agents that support HTML, the following HTML elements (in the HTML namespace) must be supported in SVG documents:

Note that the base element will affect all URL values in the document, including e.g. paint server references or use element references. However, when processing URL references to identify a specific target element, the user agent must always compare the generated absolute URL against the current document base URL to determine whether it is a same-document URL reference. In this way, target-fragment only references to elements in the same document remain valid, regardless of any changes to the document base URL.

5.11. Foreign namespaces and private data

SVG allows inclusion of elements from foreign namespaces anywhere within the SVG content. In general, the SVG user agent must include the unknown foreign-namespaced elements in the DOM but will ignore and exclude them for rendering purposes.

The notable exceptions are described in the Embedded Content chapter under HTML elements in SVG subtrees and Embedding Foreign Object Types. Also see the handling of unknown elements in the SVG namespace, which are treated differently.

Additionally, SVG allows inclusion of attributes from foreign namespaces on any SVG element. The SVG user agent must include unknown attributes in the DOM but should otherwise ignore unknown attributes.

Authors should be aware that unknown namespaced elements and attributes will not be parsed as such by the HTML parser. Instead, the namespace prefix will be included in the tag or attribute name, elements will be placed in the parent element namespace and attributes in the default namespace.

To add custom attributes in a way that will result in consistent parsing in both XML and HTML documents, authors may use the ‘data-*’ attributes. These can be added to SVG metadata elements if the information they encode is not associated with any other element in the document.

SVG's ability to include foreign namespaces can be used for the following purposes:

For example, a business graphics authoring application might want to include some private data within an SVG document so that it could properly reassemble the chart (a pie chart in this case) upon reading it back in:

<?xml version="1.0" standalone="yes"?>
<svg width="4in" height="3in"
     xmlns = 'http://www.w3.org/2000/svg'>
  <defs>
    <myapp:piechart xmlns:myapp="http://example.org/myapp"
                    title="Sales by Region">
      <myapp:pieslice label="Northern Region" value="1.23"/>
      <myapp:pieslice label="Eastern Region" value="2.53"/>
      <myapp:pieslice label="Southern Region" value="3.89"/>
      <myapp:pieslice label="Western Region" value="2.04"/>
      <!-- Other private data goes here -->
    </myapp:piechart>
  </defs>
  <desc>This chart includes private data in another namespace
  </desc>
  <!-- In here would be the actual SVG graphics elements which
       draw the pie chart -->
</svg>

5.12. Common attributes

5.12.1. Definitions

core attributes
The core attributes are those attributes that can be specified on any SVG element. This includes common attributes, and styling attributes. The core attributes are id, tabindex, lang and xml:space, class and style, and all custom data attributes.

5.12.2. Attributes common to all elements: ‘id’

The id attribute is available on all SVG elements:

Name Value Initial value Animatable
id (see below) (none) no

Must reflect the element's ID [DOM]. The id attribute must be unique within the node tree, must not be an empty string, and must not contain any whitespace characters.

Additional requirements apply in order for the id attribute to be valid in XML documents, as defined in the specification for the relevant version of XML. A stand-alone SVG document uses XML 1.0 syntax [xml], which specifies that valid id values are XML name tokens. Valid XML 1.0 names only include designated characters (letters, digits, and a few punctuation marks), and do not start with a digit, a full stop (.) character, or a hyphen-minus (-) character.

User agents should process id values in SVG files irrespective of XML validity.

Authors should avoid the use of id values that would be parsed as an SVG view specification or a basic media fragment when used as a URL target fragment.

5.12.3. The ‘lang’ and ‘xml:lang’ attributes

The ‘lang’ attribute (in no namespace) specifies the primary language for the element's contents and for any of the element's attributes that contain text.

The ‘lang’ attribute in the XML namespace is defined in XML [xml].

If these attributes are omitted from an element, then the language of this element is the same as the language of its parent element, if any.

The ‘lang’ attribute in the XML namespace may be used on SVG elements in XML documents. If both the ‘lang’ attribute in no namespace and the ‘lang’ attribute in the XML namespace are specified on the same element, they must have exactly the same value when compared in an ASCII case-insensitive manner.

If both the ‘lang’ attribute in no namespace and the ‘lang’ attribute in the XML namespace are set on an element, user agents must use the ‘lang’ attribute in the XML namespace, and the ‘lang’ attribute in no namespace must be ignored for the purposes of determining the element's language.

Name Value Initial value Animatable
lang Language-Tag [ABNF] (none) no

The ‘lang’ attribute specifies the primary language for the element's contents and for any of the element's attributes that contain text. Its value must be a valid BCP 47 language tag, or the empty string. Setting the attribute to the empty string indicates that the primary language is unknown. [BCP47].

5.12.4. The ‘xml:space’ attribute

SVG 2 Requirement: Deprecate the use of ‘xml:space’ to affect text layout and use the ‘white-space’ property instead.
Resolution: We drop xml:space from SVG 2 and remove the relating tests from the SVG 1.1. test suite.
Purpose: To align with CSS.
Owner: Chris (ACTION-3004, done; and ACTION-3005, done)
Status Done.
Name Value Initial value Animatable
xml:space (see below) default no

Deprecated XML attribute to specify whether white space is preserved in character data. The only possible values are the strings 'default' and 'preserve', without white space. Refer to the Extensible Markup Language (XML) 1.0 Recommendation [xml] and to the discussion white space handling in SVG.

New content should use the white-space property instead.

5.12.5. The ‘tabindex’ attribute

Name Value Initial value Animatable
tabindex valid integer [HTML] (none) no

This content attribute allows authors to control whether an element is focusable, whether it is supposed to be reachable using sequential focus navigation, and what is to be the relative order of the element for the purposes of sequential focus navigation.

The name "tab index" comes from the common use of the "tab" key to navigate through the focusable elements. The term "tabbing" refers to moving forward through the focusable elements that can be reached using sequential focus navigation.

5.12.6. The ‘data-*’ attributes

All SVG elements support custom data attributes, which are those in no namespace whose names begin with the string "data-". See the requirements for custom data attributes in the HTML specification.

5.13. WAI-ARIA attributes

5.13.1. Definitions

ARIA attributes
These are the attributes defined in WAI-ARIA, consisting of WAI-ARIA states and properties as well as the role attribute. See the WAI-ARIA Definition of Roles, the WAI-ARIA Graphics Module Graphics Roles, and the WAI-ARIA Supported States and Properties. The aria attributes are aria-activedescendant, role, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-atomic, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext and aria-level.

Note that the above list of ARIA attributes may be expanded by future WAI-ARIA specifications.

5.13.2. Role attribute

Any renderable element may have an ARIA role attribute specified; the role attribute is ignored on non-rendered elements. The attribute, if specified, must have a value that is a set of space-separated tokens representing the various WAI-ARIA roles that the element belongs to. These tokens are role values defined in Definition of Roles ([wai-aria], section 5.4) and Graphics Roles ([graphics-aria-1.0], section 4).

The WAI-ARIA role that an SVG element has assigned to it is the first valid role found in the list of tokens generated when the role attribute is split on spaces. A valid role is a recognized, non-abstract role that is allowed for the element type.

Name Value Initial value Animatable
role set of space-separated tokens [HTML] (see below) no

The role attribute must be a set of space-separated tokens having values defined in Definition of Roles ([wai-aria], section 5.4).

The role value is a set of white-space separated machine-extractable semantic information used to define the purpose of the element.

The initial value for the role attribute, for each SVG element, is the corresponding default implied ARIA semantic for SVG elements.

To be valid and useful, many element roles require additional information to be provided in the form of an accessible name or explicit state and property values. Accessible names may be provided using SVG descriptive elements or ARIA attributes. The requirements for each role are indicated where the role is defined, e.g., in WAI-ARIA ([WAI-ARIA]) or the WAI-ARIA Graphics Module ([graphics-aria-1.0]).

5.13.3. State and property attributes (all aria- attributes)

WAI-ARIA state and property attributes may be specified on SVG elements. These attributes are defined by ARIA in Definitions of States and Properties (all aria-* attributes) ([wai-aria], section 6.6).

These attributes, if specified, must have a value that is the WAI-ARIA value type in the "Value" field of the definition for the state or property, mapped to the appropriate SVG value type according to Mapping WAI-ARIA Value types to languages using the SVG mapping ([wai-aria], section 10.2).

The attributes are animatable; if animation is used to change the state of the graphic, or to change its content in a way that alters the correct alternative text description, the same method of animation should be used to update the corresponding ARIA state or property attribute.

WAI-ARIA State and Property attributes can be used on any element. They are not always meaningful, however, and in such cases user agents might not perform any processing aside from including them in the DOM. State and property attributes are processed according to the ARIA and SVG Accessibility API Mappings specification specifications. [wai-aria] [svg-aam-1.0]

5.13.4. Implicit and Allowed ARIA Semantics

The following table defines the default implicit ARIA semantics that apply to SVG elements. Each language feature (element) in a cell in the first column implies the ARIA semantics (role, states, and/or properties) given in the cell in the second column of the same row. The third column defines restrictions as to what WAI-ARIA semantic (role, state, or property) may or may not apply.

For many graphics elements, an implicit role is only assigned if the author provides information that indicates semantic importance. The complete inclusion criteria for the accessibility tree are defined by the SVG Accessibility API Mappings specification for user agents [svg-aam-1.0]. For authors, the preferred means of indicating semantic importance is to provide an accessible name for the element. This can be done through a direct child title element, or through the aria-label or aria-labelledby attributes. Authors should use one of these methods to provide an accessible name for any content that is essential to the comprehension of the SVG, and especially for any interactive content.

Language feature Default implied ARIA semantics Allowed roles
a link role if the element has a valid href or xlink:href attribute. For a elements that are not links, the default semantics are the same as tspan if the a element is a descendent of text, or the same as g otherwise. no restrictions
audio platform-specific role mappings, as defined in the HTML Accessibility API Mappings specification If specified, role must be application
canvas platform-specific role mappings, as defined in the HTML Accessibility API Mappings specification no restrictions
circle graphics-symbol role if the element meets the inclusion criteria, otherwise none no restrictions
clipPath none no role may be applied
cursor none no role may be applied
defs none no role may be applied
desc none no role may be applied
ellipse graphics-symbol role if the element meets the inclusion criteria, otherwise none no restrictions
feBlend none no role may be applied
feColorMatrix none no role may be applied
feComponentTransfer none no role may be applied
feComposite none no role may be applied
feConvolveMatrix none no role may be applied
feDiffuseLighting none no role may be applied
feDisplacementMap none no role may be applied
feDistantLight none no role may be applied
feDropShadow none no role may be applied
feFlood none no role may be applied
feFuncA none no role may be applied
feFuncB none no role may be applied
feFuncG none no role may be applied
feFuncR none no role may be applied
feGaussianBlur none no role may be applied
feImage none no role may be applied
feMerge none no role may be applied
feMergeNode none no role may be applied
feMorphology none no role may be applied
feOffset none no role may be applied
fePointLight none no role may be applied
feSpecularLighting none no role may be applied
feSpotLight none no role may be applied
feTile none no role may be applied
feTurbulence none no role may be applied
filter none no role may be applied
foreignObject group role if the element meets the inclusion criteria, otherwise none no restrictions
g group role if the element meets the inclusion criteria, otherwise none no restrictions
hatch none no role may be applied
hatchpath none no role may be applied
iframe platform-specific role mappings, as defined in the HTML Accessibility API Mappings specification If Specified, role must be either application, document, or img roles
image img role no restrictions
line graphics-symbol role if the element meets the inclusion criteria, otherwise none no restrictions
linearGradient none no role may be applied
marker none no role may be applied
mask none no role may be applied
mesh img role if the element meets the inclusion criteria, otherwise none no restrictions
meshgradient none no role may be applied
meshpatch none no role may be applied
meshrow none no role may be applied
metadata none no role may be applied
mpath none no role may be applied
path graphics-symbol role if the element meets the inclusion criteria, otherwise none no restrictions
pattern none no role may be applied
polygon graphics-symbol role if the element meets the inclusion criteria, otherwise none no restrictions
polyline graphics-symbol role if the element meets the inclusion criteria, otherwise none no restrictions
radialGradient none no role may be applied
rect graphics-symbol role if the element meets the inclusion criteria, otherwise none no restrictions
script none no role may be applied
solidcolor none no role may be applied
stop none no role may be applied
style none no role may be applied
svg graphics-document role no restrictions
switch none no role may be applied
symbol graphics-object role if the element is a rendered element instance that meets the inclusion criteria, otherwise none no restrictions
text grouprole, with platform-specific role mappings, as defined in the SVG Accessibility API Mappings specification no restrictions
textPath group role if the element meets the inclusion criteria, otherwise none no restrictions
title none no role may be applied
tspan group role if the element meets the inclusion criteria, otherwise none no restrictions
use graphics-object role if the element meets the inclusion criteria, otherwise none no restrictions
video platform-specific role mappings, as defined in the HTML Accessibility API Mappings specification If specified, role must be application
view none no role may be applied

5.14. DOM interfaces

5.14.1. Extensions to the Document interface

The DOM Core specification defines a Document interface, which this specification extends.

In the case where an SVG document is embedded by reference, such as when an HTML document has an ‘object’ element whose ‘data’ attribute references an SVG document (i.e., a document whose MIME type is "image/svg+xml" and whose root element is thus an svg element), there will exist two distinct DOM hierarchies. The first DOM hierarchy will be for the referencing document (e.g., an XHTML document). The second DOM hierarchy will be for the referenced SVG document.

partial interface Document {
  readonly attribute SVGSVGElement? rootElement;
};

The rootElement IDL attribute represents the root svg element. On getting rootElement, the root element of the document is returned, if it is an svg element, or null otherwise.

This attribute is deprecated, and may be removed in a future SVG specification. Authors are encouraged to use the documentElement attribute on Document instead.

SVG implementations that implement HTML must support the HTML extensions to the document interface. Other SVG implementations must support the following IDL fragment.

// must only be implemented in certain implementations
partial interface Document {
  readonly attribute DOMString title;
  readonly attribute DOMString referrer;
  readonly attribute DOMString domain;
  readonly attribute Element? activeElement;
};

The title, referrer, domain and activeElement IDL attributes must behave the same as the corresponding IDL attributes defined in HTML.

5.14.2. Interface SVGSVGElement

An SVGSVGElement object represents an svg element in the DOM. The SVGSVGElement interface also contains miscellaneous utility methods, such as data type object factory methods.

An SVGSVGElement object maintains an internal DOMPoint object, called its current translate point object, which is the object returned from the currentTranslate IDL attribute.

interface SVGSVGElement : SVGGraphicsElement {

  [SameObject] readonly attribute SVGAnimatedLength x;
  [SameObject] readonly attribute SVGAnimatedLength y;
  [SameObject] readonly attribute SVGAnimatedLength width;
  [SameObject] readonly attribute SVGAnimatedLength height;

  attribute float currentScale;
  [SameObject] readonly attribute DOMPointReadOnly currentTranslate;

  NodeList getIntersectionList(DOMRectReadOnly rect, SVGElement? referenceElement);
  NodeList getEnclosureList(DOMRectReadOnly rect, SVGElement? referenceElement);
  boolean checkIntersection(SVGElement element, DOMRectReadOnly rect);
  boolean checkEnclosure(SVGElement element, DOMRectReadOnly rect);

  void deselectAll();

  SVGNumber createSVGNumber();
  SVGLength createSVGLength();
  SVGAngle createSVGAngle();
  DOMPoint createSVGPoint();
  DOMMatrix createSVGMatrix();
  DOMRect createSVGRect();
  SVGTransform createSVGTransform();
  SVGTransform createSVGTransformFromMatrix(DOMMatrixReadOnly matrix);

  Element getElementById(DOMString elementId);

  // Deprecated methods that have no effect when called,
  // but which are kept for compatibility reasons.
  unsigned long suspendRedraw(unsigned long maxWaitMilliseconds);
  void unsuspendRedraw(unsigned long suspendHandleID);
  void unsuspendRedrawAll();
  void forceRedraw();
};

SVGSVGElement implements SVGFitToViewBox;
SVGSVGElement implements SVGZoomAndPan;
SVGSVGElement implements WindowEventHandlers;

The x, y, width and height IDL attributes reflect the computed values of the x, y, width and height properties and their corresponding presentation attributes, respectively.

The currentScale and currentTranslate IDL attributes represent the transform applied to the document in response to user magnification and panning operations, as described under Magnification and panning.

The document's magnification and panning transform is a 2x3 matrix of the form [currentScale 0 0 currentScale currentTranslate.x currentTranslate.y]. The value of the transform property does not affect currentScale or currentTranslate.

On getting currentScale, the following steps are run:

  1. If the current svg element is not the outermost svg element, then return 1.
  2. Let [a b c d e f] be the 2x3 matrix that represents the document's magnification and panning transform.
  3. Return a.

On setting currentScale, the following steps are run:

  1. If the current svg element is not the outermost svg element, then return.
  2. Let scale be the value being assigned to currentScale.
  3. Let [a b c d e f] be the 2x3 matrix that represents the document's magnification and panning transform.
  4. Set the document's magnification and panning transform to [scale 0 0 scale e f].

On getting currentTranslate, the SVGSVGElement object's current translate point object is returned. This object represents the current translation for the svg element. A current translate point object must be read only when its svg element is not the outermost svg element, and writable otherwise.

See the rules for assigning to a DOMPoint for how modifying the current translate point object affects the document's magnification and panning transform.

Whenever the document's magnification and panning transform changes in response to user interaction or whenever the outermost svg element changes, the following steps are run:

  1. Let [a b c d e f] be the 2x3 matrix that represents the document's magnification and panning transform.
  2. Let element be the outermost svg element.
  3. Update the x and y components of element's current translate point object to e and f, respectively.

Running these steps when the outermost svg element changes will ensure that if the document element is replaced with a different svg element, that its currentTranslate will be immediately updated to reflect the translation component of the document's magnification and panning transform.

Whenever an svg element is no longer outermost svg element, the x and y components of its current translate point object must be set to 0.

Note that the value of the zoomAndPan attribute on the outermost svg element only controls whether the document's magnification and panning transform can be updated through user interaction. Regardless of the value of that attribute, the current scale and translation can be changed by modifying currentScale and currentTranslate.

The suspendRedraw, unsuspendRedraw, unsuspendRedrawAll and forceRedraw methods are all deprecated and defined to have no effect. When the suspendRedraw method is called, it must return 1.

The getIntersectionList, getEnclosureList, checkIntersection and checkEnclosure methods are used to perform geometry operations on graphics elements to find those whose (or check whether their) graphical content lies partially or completely within a given rectangle.

To find the intersecting or enclosed descendants of a given element element with a given rectangle rectangle using ancestor as the element in whose coordinate space rectangle is to be interpreted, the following steps are run:

  1. Let result be an initially empty list.
  2. If element is not displayed, due to having a display value of none or being in a subtree that has failing conditional processing attributes or a failing branch of a switch, then return result.
  3. For each child element child of element, in document order:
    1. If child is an svg or g element, then:
      1. Let descendants be the result of finding the intersecting (or enclosed) descendants of child with rectangle in ancestor's coordinate space.
      2. Append to result all the elements of descendants.
    2. Otherwise, if child is a use element, then:
      1. Let root be the root of the child's shadow tree.
      2. Let descendants be the result of finding the intersecting (or enclosed) descendants of root with rectangle in ancestor's coordinate space.
      3. If descendants is not empty, then append child to result.

        This means that although we look at the the elements in the use-element shadow tree, we don't place the element instances or their corresponding element in the result list; only the use element itself is returned.

    3. Otherwise, if child is a graphics element, then:
      1. Let region be the shape in child's coordinate system that is sensitive to hit detection, taking into account the rules for interpreting child's pointer-events value.
      2. Transform region into ancestor's coordinate system.
      3. If we are finding intersecting descendants and region lies partially or fully within rectangle, then append child to result.
      4. Otherwise, we are finding enclosed descendants. If region lies fully within rectangle, then append child to result.
  4. Return result.

To find the non-container graphics elements within a given element element, the following steps are run:

  1. Let result be an initially empty list.
  2. If element is an svg or g element, then for each child element child of element, in document order:
    1. Let descendants be the result of finding the non-container graphics elements within child.
    2. Append to result all the elements of descendants.
  3. Otherwise, if element is a graphics element then append element to result.
  4. Return result.

When getIntersectionList(rect, referenceElement) or getEnclosureList(rect, referenceElement) is called, the following steps are run:

  1. Let descendants be a list, depending on what method we are in:
    getIntersectionList
    descendants is the result of finding the intersecting descendants of the current svg element with rectangle rect in the current svg element's coordinate system.
    getEnclosureList
    descendants is the result of finding the enclosed descendants of the current svg element with rectangle rect in the current svg element's coordinate system.
  2. If referenceElement is not null, then remove from descendants any element that does not have referenceElement as an ancestor.
  3. Return a static NodeList that contains all of the elements in descendants. ([DOM], section 5.2.7)

When checkIntersection(element, rect) or checkEnclosure(element, rect) is called, the following steps are run:

  1. Let descendants be a list, depending on what method we are in:
    getIntersectionList
    descendants is the result of finding the intersecting descendants of the current svg element with rectangle rect in the current svg element's coordinate system.
    getEnclosureList
    descendants is the result of finding the enclosed descendants of the current svg element with rectangle rect in the current svg element's coordinate system.
  2. Let elements be the result of finding the non-container graphics elements within element.
  3. If elements is empty, then return false.
  4. If any element in elements is not also in descendants, then return false.
  5. Return true.

The deselectAll method is used to remove any selections from the document. When deselectAll() is called, all ranges from the document's selection are removed and the selection's direction is set to forwards. [DOM][EDITING] This method is deprecated, as it duplicates functionality from the Selection API.

This is equivalent to calling document.getSelection().removeAllRanges() on the document that this svg element is in.

The createSVGNumber, createSVGLength, createSVGAngle, createSVGPoint, createSVGMatrix, createSVGRect and createSVGTransform methods are all factory functions used to create a new datatype object of a particular type. When one of these methods is called, a new object is returned according to the following table:

MethodObject and details
createSVGNumberA new, detached SVGNumber object whose value is 0.
createSVGLengthA new, detached SVGLength object whose value is the unitless <number> 0.
createSVGAngleA new, detached SVGAngle object whose value is the unitless <number> 0.
createSVGPointA new, detached DOMPoint object whose coordinates are all 0.
createSVGMatrixA new, detached DOMMatrix object representing the identity matrix.
createSVGRectA new, DOMRect object whose x, y, width and height are all 0.
createSVGTransformA new, detached SVGTransform object whose value is matrix(1, 0, 0, 1, 0, 0).

The createSVGPoint, createSVGMatrix and createSVGRect methods are all deprecated and kept only for compatibility with legacy content. Authors are encouraged to use the DOMPoint, DOMMatrix and DOMRect constructors instead.

The createSVGTransformFromMatrix method is used to create a new SVGTransform object from a matrix object. Its behavior is the same as the createSVGTransformFromMatrix method on SVGTransformList.

The getElementById method, must return the first element in tree order, within the svg element's descendants, whose ID is elementId, or null if there is no such element.

5.14.3. Interface SVGGElement

An SVGGElement object represents a g element in the DOM.

interface SVGGElement : SVGGraphicsElement {
};

5.14.4. Interface SVGUnknownElement

An SVGUnknownElement object represents an unknown element in the SVG namespace.

interface SVGUnknownElement : SVGGraphicsElement {
};

5.14.5. Interface SVGDefsElement

An SVGDefsElement object represents a defs element in the DOM.

interface SVGDefsElement : SVGGraphicsElement {
};

5.14.6. Interface SVGDescElement

An SVGDescElement object represents a desc element in the DOM.

interface SVGDescElement : SVGElement {
};

5.14.7. Interface SVGMetadataElement

An SVGMetadataElement object represents a metadata element in the DOM.

interface SVGMetadataElement : SVGElement {
};

5.14.8. Interface SVGTitleElement

An SVGTitleElement object represents a title element in the DOM.

interface SVGTitleElement : SVGElement {
};

5.14.9. Interface SVGSymbolElement

An SVGSymbolElement object represents a symbol element in the DOM.

interface SVGSymbolElement : SVGGraphicsElement {
};

SVGSymbolElement implements SVGFitToViewBox;

New in SVG 2. The SVGSymbolElement interface now inherits from SVGGraphicsElement, so that the instantiated symbol in the shadow DOM can be queried as a graphics element.

5.14.10. Interface SVGUseElement

An SVGUseElement object represents a use element in the DOM.

interface SVGUseElement : SVGGraphicsElement {
  [SameObject] readonly attribute SVGAnimatedLength x;
  [SameObject] readonly attribute SVGAnimatedLength y;
  [SameObject] readonly attribute SVGAnimatedLength width;
  [SameObject] readonly attribute SVGAnimatedLength height;
  [SameObject] readonly attribute SVGElement? instanceRoot;
  [SameObject] readonly attribute SVGElement? animatedInstanceRoot;
};

SVGUseElement implements SVGURIReference;

The x, y, width and height IDL attributes reflect the computed values of the x, y, width and height properties and their corresponding presentation attributes, respectively.

The instanceRoot and animatedInstanceRoot IDL attributes both point to the instance root, the SVGElementInstance that is a direct child of this element's shadow root (u.instanceRoot is equivalent to getting u.shadowRoot.firstChild). If this element does not have a shadow tree (for example, because its URI is invalid or because it has been disabled by conditional processing), then getting these attributes returns null.

5.14.11. Interface SVGUseElementShadowRoot

The root object of each use-element shadow tree implements the SVGUseElementShadowRoot interface. This interface does not currently define any extensions to the properties and methods defined for the ShadowRoot interface and DocumentOrShadowRoot mixin. However, the tree rooted at this node is entirely read-only from the perspective of author scripts.

interface SVGElementInstance : ShadowRoot {

};

5.14.12. Interface SVGElementInstance

The SVGElementInstance interface defines extensions to the SVGElement interface, which are only used for elements in a use-element shadow tree.

In previous versions of SVG, SVG element instances were defined as non-element objects that were valid event targets but not full DOM nodes. This specification re-defines the use-element shadow tree to be consistent with the Shadow DOM specification, which means that instances are actual SVGElement objects. This interface adds the missing functionality for backwards compatibility. However, authors should be aware that compatibility is not perfect, and design their scripts accordingly. Also note that these properties will not be available on HTML-namespaced element objects in the shadow tree.

[NoInterfaceObject]
interface SVGElementInstance {
  [SameObject] readonly attribute SVGElement? correspondingElement;
  [SameObject] readonly attribute SVGUseElement? correspondingUseElement;
};

The correspondingElement IDL attribute points to the corresponding element if this element is an element instance in a use-element shadow tree, or is null otherwise.

When the referenced element is in an external file, the presence of this pointer implies that the entire DOM of the external file must be maintained in memory. However, as currently specified, the external DOM is read-only. It therefore offers limited functionality and a potentially large performance impact. Pending feedback from implementers, authors should consider the use of correspondingElement with external file references to be at-risk.

The correspondingUseElement IDL attribute points to the corresponding use element if this element is an element instance in a use-element shadow tree, or is null otherwise.

5.14.13. Interface ShadowAnimation

The ShadowAnimation inteface defines a read-only Animation object, which mirrors all changes to the sourceAnimation object from which it was constructed. They are used to mirror author-initiated animation objects in the use-element shadow tree.

[Constructor (Animation source, Animatable newTarget) ]
interface ShadowAnimation : Animation {
  [SameObject] readonly attribute Animation sourceAnimation;
};

The sourceAnimation IDL property points to the Animation object passed in the constructor.

The constructor generates a new ShadowAnimation object, which reflects all properties on the sourceAnimation, except that its effect is created by constructing a new KeyframeEffectReadOnly using the keyframe effect of the sourceAnimation as its source, and then modifying its target to match the newTarget parameter.

A ShadowAnimation is read-only. Any attempt to set any of the inherited IDL properties, or call any of the Animation methods that change its state, must throw a NoModificationAllowedError. However, the user agent must ensure that any changes to the properties or state of the sourceAnimation are reflected in changes to the ShadowAnimation.

5.14.14. Interface SVGSwitchElement

An SVGSwitchElement object represents a switch element in the DOM.

interface SVGSwitchElement : SVGGraphicsElement {
};

5.14.15. Interface GetSVGDocument

This interface provides access to an SVG document embedded by reference in another DOM-based language. The expectation is that the interface is implemented on DOM objects that allow such SVG document references.

This interface is deprecated and may be dropped from future versions of the SVG specification. To access the SVG document inside an ‘iframe’ or ‘object’ element, authors are suggested to use the contentDocument attribute on the HTMLIFrameElement or HTMLObjectElement interface, respectively.

The HTMLIFrameElement, HTMLEmbedElement and HTMLObjectElement interfaces all define their own getSVGDocument method, which provides access to the SVG document in the same way that the GetSVGDocument does. Those three interfaces therefore do not need to implement GetSVGDocument. Still, authors are strongly recommended to use contentDocument instead.

[NoInterfaceObject]
interface GetSVGDocument {
  Document getSVGDocument();
};

The getSVGDocument method is used to return a referenced SVG document. When getSVGDocument() is called, it must return the Document object referenced by the embedding element that implements the GetSVGDocument interface; if there is no document, null is returned.

Note that this does no check to see whether the referenced document is indeed an SVG document. Instead, any document is returned.


Chapter 6: Styling

6.1. Styling SVG content using CSS

Elements in an SVG document can be styled using CSS. Most visual characteristics and some aspects of element geometry are controlled using CSS properties. For example, the fill property controls the paint used to fill the inside of a shape, and the width and height properties are used to control the size of a rect element.

SVG user agents must support all of the CSS styling mechanisms described in this chapter.

In SVG 1.1, support for inline style sheets using the style element and style was not required. In SVG 2, these are required.

6.2. Inline style sheets: the ‘style’ element

SVG 2 Requirement: Add HTML5 ‘style’ element attributes to SVG's style element.
Resolution: SVG 2 ‘style’ element shall be aligned with the HTML5 ‘style’ element.
Purpose: To not surprise authors with different behavior for the ‘style’ element in HTML and SVG content.
Owner: Cameron (ACTION-3277)

The style element allows style sheets to be embedded directly within SVG content. SVG's style element has the same attributes as the corresponding element in HTML.

style
Categories:
Never-rendered element
Content model:
Character data.
Attributes:
DOM Interfaces:

Attribute definitions:

Name Value Initial value Animatable
type (see below) text/css no

This attribute specifies the style sheet language of the element's contents, as a media type. [rfc2046]. If the attribute is not specified, then the style sheet language is assumed to be CSS.

Name Value Initial value Animatable
media (see below) all no

This attribute specifies a media query that must be matched for the style sheet to apply. Its value is parsed as a media_query_list. If not specified, the style sheet applies unconditionally.

Name Value Initial value Animatable
title (see below) (none) no

This attribute specifies a title for the style sheet, which is used when exposing and selecting between alternate style sheets. The attribute takes any value.

The semantics and processing of a style and its attributes must be the same as is defined for the HTML ‘style’ element.

The style sheet's text content is never directly rendered; the display value for the style element must always be set to none by the user agent style sheet, and this declaration must have importance over any other CSS rule or presentation attribute.

6.3. External style sheets: the effect of the HTML ‘link’ element

An HTML ‘link’ element in an SVG document (that is, an element in the HTML namespace with local name "link") with its ‘rel’ attribute set to 'stylesheet' must be processed as defined in the HTML specification and cause external style sheets to be loaded and applied to the document. Such elements in HTML documents outside of an inline SVG fragment must also apply to the SVG content.

Because the element is required to be in the HTML namespace, it is not possible for an HTML ‘link’ element to be parsed as part of an inline SVG fragment in a text/html document. However, when parsing an SVG document using XML syntax, XML namespace declarations can be used to place the element in the HTML namespace.

Note that an alternative way to reference external style sheets without using the HTML ‘link’ element is to use an @import rule in an inline style sheet. For example:

<svg xmlns="http://www.w3.org/2000/svg">
  <style>
    @import url(mystyles.css);
  </style>
  <rect .../>
</svg>

would behave similarly to:

<svg xmlns="http://www.w3.org/2000/svg">
  <link xmlns="http://www.w3.org/1999/xhtml" rel="stylesheet" href="mystyles.css" type="text/css"/>
  <rect .../>
</svg>

Or, in XML documents, external CSS style sheets may be included using the <?xml-stylesheet?> processing instruction [xml-stylesheet].

6.4. Style sheets in HTML documents

When an SVG style or an HTML ‘style’ element is used in an HTML document, those style sheets must apply to all HTML and inline SVG content in the document. Similarly, any HTML ‘style’ element used in an SVG document must also apply its style sheet to the document.

6.5. Element-specific styling: the ‘class’ and ‘style’ attributes

As with HTML, SVG supports the class and style attributes on all elements to support element-specific styling.

Attribute definitions:

Name Value Initial value Animatable
class set of space-separated tokens [HTML] (none) yes

The class attribute assigns one or more class names to an element, which can then be used for addressing by the styling language.

Name Value Initial value Animatable
style (see below) (none) no

The style attribute is used to supply a CSS declaration of an element. The attribute is parsed as a declaration-list.

Aside from the way that the class attribute is reflected in the SVG DOM (in the className IDL attribute on SVGElement), the semantics and behavior of the class and style attributes must be the same as that for the corresponding attributes in HTML.

In the following example, the text element is used in conjunction with the class attribute to markup document messages. Messages appear in both English and French versions.

<!-- English messages -->
<text class="info" lang="en">Variable declared twice</text>
<text class="warning" lang="en">Undeclared variable</text>
<text class="error" lang="en">Bad syntax for variable name</text>
<!-- French messages -->
<text class="info" lang="fr">Variable déclarée deux fois</text>
<text class="warning" lang="fr">Variable indéfinie</text>
<text class="error" lang="fr">Erreur de syntaxe pour variable</text>

The following CSS style rules would tell visual user agents to display informational messages in green, warning messages in yellow, and error messages in red:

text.info    { fill: green; }
text.warning { fill: yellow; }
text.error   { fill: red; }

This example shows how the style attribute can be used to style text elements similarly to the previous example:

<text style="fill: green;" lang="en">Variable declared twice</text>
<text style="fill: yellow;" lang="en">Undeclared variable</text>
<text style="fill: red;" lang="en">Bad syntax for variable name</text>

6.6. Presentation attributes

Some styling properties can be specified not only in style sheets and style attributes, but also in presentation attributes. These are attributes whose name matches (or is similar to) a given CSS property and whose value is parsed as a value of that property. Presentation attributes contribute to the author level of the cascade, following all other author-level style sheets, and have specificity 0.

Since presentation attributes are parsed as CSS values, not declarations, an !important declaration within a presentation attribute will cause it to have an invalid value. See Attribute syntax for details on how presentation attributes are parsed.

Not all style properties that can affect SVG rendering have a corresponding presentation attribute. Other attributes (which happen to share the name of a style property) must not be parsed as a presentation attribute and must not affect CSS cascading and inheritance. Also, only elements in the SVG namespace support presentation attributes. Most SVG presentation attributes may be specified on any element in the SVG namespace where there is not a name clash with an existing attribute. However, the geometry properties only have equivalent presentation attributes on designated elements. Attributes of the same name on other elements must not affect CSS cascading and inheritance.

Except as noted in the table for the transform presentation attributes, the presentation attribute name is the same as the property name, in lower-case letters.

Properties with a presentation attribute Elements that support the presentation attribute
cx, cy circle and ellipse
height, width, x, y foreignObject, image, rect, svg, symbol, and use
r circle
rx, ry ellipse and rect
d path
fill Any element in the SVG namespace except for animation elements, which have a different fill attribute.
transform Any element in the SVG namespace; however, for historical reasons the linearGradient and radialGradient elements use the attribute name gradientTransform, and the pattern element uses patternTransform.
alignment-baseline, baseline-shift, clip, clip-path, clip-rule, color, color-interpolation, color-interpolation-filters, color-rendering, cursor, direction, display, dominant-baseline, fill-opacity, fill-rule, filter, flood-color, flood-opacity, font-family, font-size, font-size-adjust, font-stretch, font-style, font-variant, font-weight, glyph-orientation-horizontal, glyph-orientation-vertical, image-rendering, letter-spacing, lighting-color, marker-end, marker-mid, marker-start, mask, opacity, overflow, pointer-events, shape-rendering, solid-color, solid-opacity, stop-color, stop-opacity, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, text-anchor, text-decoration, text-overflow, text-rendering, unicode-bidi, vector-effect, visibility, white-space, word-spacing, writing-mode Any element in the SVG namespace.

Since presentation attributes are only available on elements in the SVG namespace, an HTML video element is classified as a graphics element, for example, but does not support any presentation attributes.

Note that ‘cx’, ‘cy’, ‘r’, ‘x’, ‘y’, ‘width’ and ‘height’ attributes are not always presentation attributes. For example, the x attribute on text and tspan is not a presentation attribute for the x property, and the r attribute on a radialGradient is not a presentation attribute for the r property.

In the future, any new properties that apply to SVG content will not gain presentation attributes. Therefore, authors are suggested to use styling properties, either through inline style properties or style sheets, rather than presentation attributes, for styling SVG content.

Animation of presentation attributes is equivalent to animating the corresponding property.

6.7. Required properties

The following properties must be supported by all SVG user agents:

6.8. User agent style sheet

The following user agent style sheet must be applied in all SVG user agents.

@namespace url(http://www.w3.org/2000/svg);
@namespace xml url(http://www.w3.org/XML/1998/namespace);

svg:not(:root), hatch, image, marker, pattern, symbol { overflow: hidden; }

*:not(svg),
*:not(foreignObject) > svg {
  transform-origin: 0 0;
}

*[xml|space=preserve] {
  text-space-collapse: preserve-spaces;
}

defs, 
clipPath, mask, marker, 
desc, title, metadata, 
pattern, hatch,
linearGradient, radialGradient, meshGradient, 
script, style,
symbol {
  display: none !important;
}
:host(use) > symbol {
  display: inline !important;
}

In addition, all interactive user agents are required to apply distinctive styles to the :focus pseudo-class (normally using the outline property) and the ::selection pseudo-element (using an appropriate highlighting technique, such as redrawing the selected glyphs with inverse colors).

An !important rule in a user agent stylesheet over-rides all user and author styles [css-cascade-4]. The display value for never-rendered elements and for symbol elements can therefore not be changed. A symbol must only be rendered if it is the direct child of a shadow root whose host is a use element (and must always be rendered if the host use element is rendered). The other elements, and their child content, are never rendered directly.

CSS Transforms defines that the initial value for transform-origin is 50% 50%. Since elements in SVG must, by default, transform around their origin at (0, 0), transform-origin is overridden and set to a default value of 0 0 for all SVG elements (except for root svg elements and svg elements that are the child of a foreignObject element or an element in a non-SVG namespace; these elements must transform around their center). [css-transforms-1]

The OpenType specification requires an additional user agent style sheet to be applied when processing [OPENTYPE]. It is as follows:

@namespace svg url(http://www.w3.org/2000/svg);

svg|text, svg|foreignObject {
  display: none !important;
}

:root {
  fill: context-fill;
  fill-opacity: context-fill-opacity;
  stroke: context-stroke;
  stroke-opacity: context-stroke-opacity;
  stroke-width: context-value;
  stroke-dasharray: context-value;
  stroke-dashoffset: context-value;
}

The context-fill and context-stroke keywords are as defined in this specification, where the context element for a font glyph is the corresponding text content element. The other keywords are as defined in the OpenType specification, and ensure that the style values from the text content element are propagated to the font glyphs, with appropriate adjustments for the change in the coordinate system [OPENTYPE].

6.9. Required CSS features

Besides the features described above, the following CSS features must be also supported in SVG user agents:

6.10. DOM interfaces

6.10.1. Interface SVGStyleElement

An SVGStyleElement object represents a style element in the DOM.

interface SVGStyleElement : SVGElement {
  attribute DOMString type;
  attribute DOMString media;
  attribute DOMString title;
};

SVGStyleElement implements LinkStyle;

The type, media and title IDL attributes reflect the type, media and title content attributes, respectively.


Chapter 7: Geometry Properties

Beside SVG's styling properties, SVG also defines geometry properties. Geometry properties describe the position and dimension of the graphics elements circle, ellipse, rect, image, foreignObject and the svg element.

7.1. Horizontal center coordinate: The ‘cx’ property

Name: cx
Value: <length> | <percentage>
Initial: 0
Applies to: circle and ellipse
Inherited: no
Percentages: refer to the size of the current SVG viewport (see Units)
Media: visual
Computed value: absolute length or percentage
Animatable: yes

The cx property describes the horizontal center coordinate of the position of the element.

7.2. Vertical center coordinate: The ‘cy’ property

Name: cy
Value: <length> | <percentage>
Initial: 0
Applies to: circle and ellipse
Inherited: no
Percentages: refer to the size of the current SVG viewport (see Units)
Media: visual
Computed value: absolute length or percentage
Animatable: yes

The cy property describes the vertical center coordinate of the position of the element.

7.3. Radius: The ‘r’ property

Name: r
Value: <length> | <percentage>
Initial: 0
Applies to: circle
Inherited: no
Percentages: refer to the size of the current SVG viewport (see Units)
Media: visual
Computed value: absolute length or percentage
Animatable: yes

The r property describes the radius of the circle element.

A negative value for r must be treated as an illegal value.

7.4. Horizontal radius: The ‘rx’ property

Name: rx
Value: <length> | <percentage> | auto
Initial: auto
Applies to: ellipse, rect
Inherited: no
Percentages: refer to the size of the current SVG viewport (see Units)
Media: visual
Computed value: absolute length or percentage
Animatable: yes

The rx property describes the horizontal radius of the ellipse element and the curve radius of the rect element. When the computed value of ‘rx’ is auto, the used radius is equal to the absolute length used for ry, creating a circular arc. If both ‘rx’ and ‘ry’ have a computed value of auto, the used value is 0.

Regardless of how the value is calculated, the used value of ‘rx’ for a rect is never more than 50% of the used value of width for the same shape.

The auto behavior is new in SVG 2 for ellipse, matching the behavior for rect elements when rx was not specified.

A negative value for rx must be treated as an illegal value.

7.5. Vertical radius: The ‘ry’ property

Name: ry
Value: <length> | <percentage> | auto
Initial: auto
Applies to: ellipse, rect
Inherited: no
Percentages: refer to the size of the current SVG viewport (see Units)
Media: visual
Computed value: absolute length or percentage
Animatable: yes

The ry property describes the vertical radius of the ellipse element and the vertical curve radius of the rect element. When the computed value of ‘ry’ is auto, the used radius is equal to the absolute length used for rx, creating a circular arc. If both ‘rx’ and ‘ry’ have a computed value of auto, the used value is 0.

Regardless of how the value is calculated, the used value of ‘ry’ for a rect is never more than 50% of the used value of height for the same shape.

The auto behavior is new in SVG 2 for ellipse, matching the behavior for rect elements when ry was not specified.

A negative value for ry must be treated as an illegal value.

7.6. Horizontal coordinate: The ‘x’ property

Name: x
Value: <length> | <percentage>
Initial: 0
Applies to: svg, rect, image, foreignObject
Inherited: no
Percentages: refer to the size of the current SVG viewport (see Units)
Media: visual
Computed value: absolute length or percentage
Animatable: yes

The x property describes the horizontal coordinate of the position of the element.

7.7. Vertical coordinate: The ‘y’ property

Name: y
Value: <length> | <percentage>
Initial: 0
Applies to: svg, rect, image, foreignObject
Inherited: no
Percentages: refer to the size of the current SVG viewport (see Units)
Media: visual
Computed value: absolute length or percentage
Animatable: yes

The y property describes the vertical coordinate of the position of the element.

7.8. Sizing properties: the effect of the ‘width’ and ‘height’ properties

See the CSS 2.1 specification for the definitions of width and height.

The CSS width and height properties are used for sizing some SVG elements. Specifically, they are used to size rect, svg, image and foreignObject. All of these elements have ‘width’ and ‘height’ presentation attributes. The properties are also used for laying out embedded elements from the HTML namespace.

The used value of width may be constrained by the value of the max-width and min-width properties. The used value of height may be constrained by the value of the max-height and min-height properties.

The value auto for width and height on the svg element is treated as 100%.

The value auto for width and height on the image element is calculated from the referenced image's intrinsic dimensions and aspect ratio, according to the CSS default sizing algorithm.

New in SVG 2. Images embedded in SVG can now be auto-sized to the intrinsic size, or scaled to a fixed height or width according to the intrinsic aspect ratio. This matches the behavior of embedded images in HTML.

The value auto for width and height on other elements is treated as 0.

This means that, for example, a foreignObject object element will not shrink-wrap to its contents if auto is used.


Chapter 8: Coordinate Systems, Transformations and Units

8.1. Introduction

All SVG content is drawn inside SVG viewports. Every SVG viewport defines a drawing region characterized by a size (width, height), and an origin, measured in abstract user units.

Note that the term SVG viewport is distinct from the "viewport" term used in CSS.

The initial viewport is a top-level SVG viewport that establishes a mapping between the coordinate system used by the containing environment (for example, CSS pixels in web browsers) and user units. Establishing an initial viewport is described in more detail in The initial viewport.

SVG viewports are only established by elements. See Establishing a new SVG viewport for information on which elements generate viewports.

Each SVG viewport generates a viewport coordinate system and a local coordinate system, initially identical. Providing a viewBox on a viewport's element transforms the local coordinate system relative to the viewport coordinate system as described in The viewBox attribute. Child elements of a viewport can further modify the local coordinate system, for example by specifying the transform property.

SVG viewports can be nested. Percentage units are resolved with reference to the width and height of the nearest ancestral SVG viewport. Hence, nesting SVG viewports provides an opportunity to redefine the meaning of percentage units and provide a new reference rectangle for "fitting" a graphic relative to a particular rectangular area.

The width, height and origin of SVG viewports is established by a negotiation process between the SVG document fragment generating the SVG viewport, and the parent of that fragment (whether real or implicit). See Establishing a new SVG viewport for a description of this negotiation process.

By default, a nested SVG viewport's viewport coordinate system is equivalent to the local coordinate system of the parent element, translated by the origin of the SVG viewport's element. However, a transform property on an SVG viewport's element will modify the viewport coordinate system relative to the parent element's local coordinate system.

Abstractly, all SVG viewports are embedded in the canvas, a drawing region that is infinitely large in all relevant dimensions.

8.2. Computing the equivalent transform of an SVG viewport

This process converts the min-x, min-y, width and height values of a viewBox attribute, the position and size of the element on which the viewBox attribute is defined, and the value of the preserveAspectRatio attribute on that element into a translation and a scale that is applied to content contained by the element.

  1. Let vb-x, vb-y, vb-width, vb-height be the min-x, min-y, width and height values of the viewBox attribute respectively.
  2. Let e-x, e-y, e-width, e-height be the position and size of the element respectively.
  3. Let align be the align value of preserveAspectRatio, or 'xMidYMid' if preserveAspectRatio is not defined.
  4. Let meetOrSlice be the meetOrSlice value of preserveAspectRatio, or 'meet' if preserveAspectRatio is not defined or if meetOrSlice is missing from this value.
  5. Initialize scale-x to e-width/vb-width.
  6. Initialize scale-y to e-height/vb-height.
  7. If align is not 'none' and meetOrSlice is 'meet', set the larger of scale-x and scale-y to the smaller.
  8. Otherwise, if align is not 'none' and meetOrSlice is 'slice', set the smaller of scale-x and scale-y to the larger.
  9. Initialize translate-x to e-x - (vb-x * scale-x).
  10. Initialize translate-y to e-y - (vb-y * scale-y)
  11. If align contains 'xMid', add (e-width - vb-width * scale-x) / 2 to translate-x.
  12. If align contains 'xMax', add (e-width - vb-width * scale-x) to translate-x.
  13. If align contains 'yMid', add (e-height - vb-height * scale-y) / 2 to translate-y.
  14. If align contains 'yMax', add (e-height - vb-height * scale-y) to translate-y.

The transform applied to content contained by the element is given by translate(translate-x, translate-y) scale(scale-x, scale-y).

8.3. The initial viewport

The initial viewport's width, must be the value of the width presentation attribute on the outermost svg element, unless the following conditions are met:

Under these conditions, the viewport's width must be established via the positioning properties.

Similarly, if there are positioning properties specified on the referencing element or on the outermost svg element that are sufficient to establish the height of the viewport, then these positioning properties must establish the viewport's height; otherwise, the initial viewport's height must be the value of the height presentation attribute on the outermost svg element.

If the width or height presentation attributes on the outermost svg element are in user units (i.e., no unit identifier has been provided), then the value is assumed to be equivalent to the same number of "px" units (see Units).

In the following example, an SVG graphic is embedded inline within a parent XML document which is formatted using CSS layout rules. Since CSS positioning properties are not provided on the outermost svg element, the width="100px" and height="200px" attributes determine the size of the initial viewport:

<?xml version="1.0" standalone="yes"?>
<parent xmlns="http://some.url">

   <!-- SVG graphic -->
   <svg xmlns='http://www.w3.org/2000/svg'
      width="100px" height="200px">
      <path d="M100,100 Q200,400,300,100"/>
      <!-- rest of SVG graphic would go here -->
   </svg>

</parent>

8.4. The initial coordinate system

For the outermost svg element, the SVG user agent must determine an initial viewport coordinate system and an initial local coordinate system such that the two coordinates systems are identical. The origin of both coordinate systems must be at the origin of the SVG viewport, and one unit in the initial coordinate system must equal one CSS 2.1 px ([CSS2], section 4.3.2) in the SVG viewport. In stand-alone SVG documents and in SVG document fragments embedded (by reference or inline) within parent documents where the parent's layout is determined by CSS [CSS2] or XSL [XSL], the initial viewport coordinate system (and therefore the initial user coordinate system) must have its origin at the top/left of the viewport, with the positive x-axis pointing towards the right, the positive y-axis pointing down, and text rendered with an "upright" orientation, which means glyphs are oriented such that Roman characters and full-size ideographic characters for Asian scripts have the top edge of the corresponding glyphs oriented upwards and the right edge of the corresponding glyphs oriented to the right.

If the SVG implementation is part of a user agent which supports styling documents using CSS 2.1 compatible px units, then the SVG user agent should set its initial value for the size of a px unit in real world units to match the value used for other styling operations; otherwise, if the user agent can determine the size of a px unit from its environment, it should use that value; otherwise, it should choose an appropriate size for one px unit. In all cases, the size of a px must be in conformance with the rules described in CSS 2.1 ([CSS2], section 4.3.2).

Example InitialCoords below shows that the initial coordinate system has the origin at the top/left with the x-axis pointing to the right and the y-axis pointing down. The initial user coordinate system has one user unit equal to the parent (implicit or explicit) user agent's "pixel".

<?xml version="1.0" standalone="no"?>
<svg width="300px" height="100px" version="1.1"
     xmlns="http://www.w3.org/2000/svg">
  <desc>Example InitialCoords - SVG's initial coordinate system</desc>

  <g fill="none" stroke="black" stroke-width="3" >
    <line x1="0" y1="1.5" x2="300" y2="1.5" />
    <line x1="1.5" y1="0" x2="1.5" y2="100" />
  </g>
  <g fill="red" stroke="none" >
    <rect x="0" y="0" width="3" height="3" />
    <rect x="297" y="0" width="3" height="3" />
    <rect x="0" y="97" width="3" height="3" />
  </g>
  <g font-size="14" font-family="Verdana" >
    <text x="10" y="20">(0,0)</text>
    <text x="240" y="20">(300,0)</text>
    <text x="10" y="90">(0,100)</text>
  </g>
</svg>
Example InitialCoords — SVG's initial coordinate system

Example InitialCoords

View this example as SVG (SVG-enabled browsers only)

8.5. The ‘transform’ property

User agents must support the transform property and presentation attribute as defined in [css-transforms-1].

8.6. The ‘viewBox’ attribute

Name Value Initial value Animatable
viewBox [<min-x>,? <min-y>,? <width>,? <height>] As if not specified. yes
<min-x>, <min-x>, <width>, <height> = <number>

Transform on the svg element is a bit special due to the viewBox attribute. The transform should be applied as if the svg had a parent element with that transform set.

RESOLUTION: transform property applies conceptually to the outside of the 'svg' element and there is no difference between presentation attribute and style property (in terms of the visual result).

The viewBox attribute, in conjunction with the preserveAspectRatio attribute, provides the capability to stretch an SVG viewport to fit a particular container element.

The value of the viewBox attribute is a list of four numbers <min-x>, <min-y>, <width> and <height>, separated by whitespace and/or a comma, that specify a rectangle in user space that should be mapped to the bounds of the SVG viewport established by the given element, taking into account the preserveAspectRatio attribute. The presence of the viewBox attribute results in a transformation being applied to the viewport coordinate system as described in Computing the equivalent transform of an SVG viewport.

A negative value for <width> or <height> is an error and invalidates the viewBox attribute. A value of zero disables rendering of the element.

Example ViewBox illustrates the use of the viewBox attribute on the outermost svg element to specify that the SVG content should stretch to fit bounds of the SVG viewport.

<?xml version="1.0" standalone="no"?>
<svg width="300px" height="200px"
     viewBox="0 0 1500 1000" preserveAspectRatio="none"
     xmlns="http://www.w3.org/2000/svg">
  <desc>Example ViewBox - uses the viewBox
   attribute to automatically create an initial user coordinate
   system which causes the graphic to scale to fit into the
   SVG viewport no matter what size the SVG viewport is.</desc>
  <!-- This rectangle goes from (0,0) to (1500,1000) in local coordinate system.
       Because of the viewBox attribute above,
       the rectangle will end up filling the entire area
       reserved for the SVG content. -->
  <rect x="0" y="0" width="1500" height="1000"
        fill="yellow" stroke="blue" stroke-width="12"  />
  <!-- A large, red triangle -->
  <path fill="red"  d="M 750,100 L 250,900 L 1250,900 z"/>
  <!-- A text string that spans most of the SVG viewport -->
  <text x="100" y="600" font-size="200" font-family="Verdana" >
    Stretch to fit
  </text>
</svg>
Example ViewBox
Rendered into
SVG viewport with
width=300px,
height=200px
      Rendered into
SVG viewport with
width=150px,
height=200px
Example ViewBox - stretch to fit 300 by 200       Example ViewBox - stretch to fit 150 by 200

View this example as SVG (SVG-enabled browsers only)
 

The effect of the viewBox attribute is that the user agent automatically supplies the appropriate transformation matrix to map the specified rectangle in local coordinate system to the bounds of a designated region (often, the SVG viewport). To achieve the effect of the example on the left, with SVG viewport dimensions of 300 by 200 pixels, the user agent needs to automatically insert a transformation which scales both X and Y by 0.2. The effect is equivalent to having an SVG viewport of size 300px by 200px and the following supplemental transformation in the document, as follows:

<?xml version="1.0" standalone="no"?>
<svg width="300px" height="200px"
     xmlns="http://www.w3.org/2000/svg">
  <g transform="scale(0.2)">
    <!-- Rest of document goes here -->
  </g>
</svg>

To achieve the effect of the example on the right, with SVG viewport dimensions of 150 by 200 pixels, the user agent needs to automatically insert a transformation which scales X by 0.1 and Y by 0.2. The effect is equivalent to having an SVG viewport of size 150px by 200px and the following supplemental transformation in the document, as follows:

<?xml version="1.0" standalone="no"?>
<svg width="150px" height="200px"
     xmlns="http://www.w3.org/2000/svg">
  <g transform="scale(0.1 0.2)">
    <!-- Rest of document goes here -->
  </g>
</svg>

Note that in some cases the user agent will need to supply a translate transformation in addition to a scale transformation. For example, on an outermost svg element, a translate transformation will be needed if the viewBox attributes specifies values other than zero for <min-x> or <min-y>.

If both transform (or patternTransform) and viewBox are applied to an element two new coordinate systems are established. transform establishes the first new coordinate system for the element. viewBox establishes a second coordinate system for all descendants of the element. The first coordinate system is post-multiplied by the second coordinate system.

Unlike the transform property, the automatic transformation that is created due to a viewBox does not affect the ‘x’, ‘y’, ‘width’ and ‘height’ attributes (or in the case of the marker element, the markerWidth and markerHeight attributes) on the element with the viewBox attribute. Thus, in the example above which shows an svg element which has width and height presentation attributes and a viewBox attribute, the width and height represent values in the coordinate system that exists before the viewBox transformation is applied. On the other hand, like the transform property, it does establish a new coordinate system for all other attributes and for descendant elements.

8.7. The ‘preserveAspectRatio’ attribute

Name Value Initial value Animatable
preserveAspectRatio <align> <meetOrSlice>? xMidYMid meet yes
<align> = 
    none
    | xMinYMin | xMidYMin | xMaxYMin
    | xMinYMid | xMidYMid | xMaxYMid
    | xMinYMax | xMidYMax | xMaxYMax
<meetOrSlice> = meet | slice

Indicates whether or not to force uniform scaling. Applies to all elements that establish a new SVG viewport (see elements that establish SVG viewports), plus the image, marker, pattern and view elements

In some cases, typically when using the viewBox attribute, it is desirable that the graphics stretch to fit non-uniformly to take up the entire SVG viewport. In other cases, it is desirable that uniform scaling be used for the purposes of preserving the aspect ratio of the graphics.

For elements that establish a new SVG viewport (see elements that establish SVG viewports), plus the marker, pattern and view elements, preserveAspectRatio only applies when a value has been provided for viewBox on the same element. For these elements, if attribute viewBox is not provided, then preserveAspectRatio is ignored.

For image elements, preserveAspectRatio indicates how referenced images should be fitted with respect to the reference rectangle and whether the aspect ratio of the referenced image should be preserved with respect to the current user coordinate system.

The <align> parameter indicates whether to force uniform scaling and, if so, the alignment method to use in case the aspect ratio of the viewBox doesn't match the aspect ratio of the SVG viewport. The <align> parameter must be one of the following strings:

The <meetOrSlice> parameter is optional and, if provided, is separated from the <align> value by one or more spaces and then must be one of the following strings:

Example PreserveAspectRatio illustrates the various options on preserveAspectRatio. The example creates several new SVG viewports by including svg sub-elements embedded inside the outermost svg element (see Establishing a new SVG viewport).

<svg width="450px" height="300px" xmlns="http://www.w3.org/2000/svg">

  <desc>Example PreserveAspectRatio - illustrates preserveAspectRatio attribute</desc>

  <style type="text/css">
    text { font-size: 9; }
    rect { fill: none; stroke: blue; }
  </style>

  <defs>
    <g id="smile">
      <rect x='.5' y='.5' width='29' height='39' style="fill:black;stroke:red"/>
      <circle cx='15' cy='20' r='10'  fill='yellow'/>
      <circle cx='12' cy='17' r='1.5' fill='black'/>
      <circle cx='17' cy='17' r='1.5' fill='black'/>
      <path d='M 10 24 A 8 8 0 0 0 20 24' stroke='black' stroke-width='2'/>
    </g>
  </defs>

  <rect x="1" y="1" width="448" height="298"/>

  <text x="10" y="30">SVG to fit</text>
  <g transform="translate(20,40)"><use href="#smile" /></g>

  <text x="10" y="110">Viewport 1</text>
  <g transform="translate(10,120)"><rect x='.5' y='.5' width='49' height='29'/></g>

  <text x="10" y="180">Viewport 2</text>
  <g transform="translate(20,190)"><rect x='.5' y='.5' width='29' height='59'/></g>

  <g id="meet-group-1" transform="translate(100, 60)">
    <text x="0" y="-30">--------------- meet ---------------</text>
    <g>
      <text y="-10">xMin*</text>
      <rect x='.5' y='.5' width='49' height='29'/>
      <svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 30 40" width="50" height="30">
	<use href="#smile" />
      </svg>
    </g>
    <g transform="translate(70,0)">
      <text y="-10">xMid*</text>
      <rect x='.5' y='.5' width='49' height='29'/>
      <svg preserveAspectRatio="xMidYMid meet" viewBox="0 0 30 40" width="50" height="30">
	<use href="#smile" />
      </svg>
    </g>
    <g transform="translate(0,70)">
      <text y="-10">xMax*</text>
      <rect x='.5' y='.5' width='49' height='29'/>
      <svg preserveAspectRatio="xMaxYMax meet" viewBox="0 0 30 40" width="50" height="30">
        <use href="#smile" />
      </svg>
    </g>
  </g>

  <g id="meet-group-2" transform="translate(250, 60)">
    <text x="0" y="-30">---------- meet ----------</text>
    <g>
      <text y="-10">*YMin</text>
      <rect  x='.5' y='.5' width='29' height='59'/>
      <svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 30 40" width="30" height="60">
	<use href="#smile" />
      </svg>
    </g>
    <g transform="translate(50, 0)">
      <text y="-10">*YMid</text>
      <rect x='.5' y='.5' width='29' height='59'/>
      <svg preserveAspectRatio="xMidYMid meet" viewBox="0 0 30 40" width="30" height="60">
	<use href="#smile" />
      </svg>
    </g>
    <g transform="translate(100, 0)">
      <text y="-10">*YMax</text>
      <rect x='.5' y='.5' width='29' height='59'/>
      <svg preserveAspectRatio="xMaxYMax meet" viewBox="0 0 30 40" width="30" height="60">
	<use href="#smile" />
      </svg>
    </g>
  </g>

  <g id="slice-group-1" transform="translate(100, 220)">
    <text x="0" y="-30">---------- slice ----------</text>
    <g>
      <text y="-10">xMin*</text>
      <rect x='.5' y='.5' width='29' height='59'/>
      <svg preserveAspectRatio="xMinYMin slice" viewBox="0 0 30 40" width="30" height="60">
	<use href="#smile" />
      </svg>
    </g>
    <g transform="translate(50,0)">
      <text y="-10">xMid*</text>
      <rect x='.5' y='.5' width='29' height='59'/>
      <svg preserveAspectRatio="xMidYMid slice" viewBox="0 0 30 40" width="30" height="60">
	<use href="#smile" />
      </svg>
    </g>
    <g transform="translate(100,0)">
      <text y="-10">xMax*</text>
      <rect x='.5' y='.5' width='29' height='59'/>
      <svg preserveAspectRatio="xMaxYMax slice" viewBox="0 0 30 40" width="30" height="60">
	<use href="#smile" />
      </svg>
    </g>
  </g>

  <g id="slice-group-2" transform="translate(250, 220)">
    <text x="0" y="-30">--------------- slice ---------------</text>
    <g>
      <text y="-10">*YMin</text>
      <rect x='.5' y='.5' width='49' height='29'/>
      <svg preserveAspectRatio="xMinYMin slice" viewBox="0 0 30 40"
           width="50" height="30">
	<use href="#smile" />
      </svg>
    </g>
    <g transform="translate(70,0)">
      <text y="-10">*YMid</text>
      <rect x='.5' y='.5' width='49' height='29'/>
      <svg preserveAspectRatio="xMidYMid slice" viewBox="0 0 30 40" width="50" height="30">
	<use href="#smile" />
      </svg>
    </g>
    <g transform="translate(140,0)">
      <text y="-10">*YMax</text>
      <rect x='.5' y='.5' width='49' height='29'/>
      <svg preserveAspectRatio="xMaxYMax slice" viewBox="0 0 30 40" width="50" height="30">
	<use href="#smile" />
      </svg>
    </g>
  </g>
</svg>
Example PreserveAspectRatio — demonstrate available options

Example PreserveAspectRatio

8.8. Establishing a new SVG viewport

At any point in an SVG drawing, you can establish a new SVG viewport into which all contained graphics is drawn by including an svg element inside SVG content. By establishing a new SVG viewport, you also implicitly establish a new viewport coordinate system, a new user coordinate system. Additionally, there is a new meaning for percentage units defined to be relative to the current SVG viewport since a new SVG viewport has been established (see Units).

The bounds of the new SVG viewport are defined by the ‘x’, ‘y’, ‘width’ and ‘height’ attributes on the element establishing the new SVG viewport, such as an svg element. Both the new viewport coordinate system and the new user coordinate system have their origins at (‘x’, ‘y’), where ‘x’ and ‘y’ represent the value of the corresponding attributes on the element establishing the SVG viewport. The orientation of the new viewport coordinate system and the new user coordinate system correspond to the orientation of the current user coordinate system for the element establishing the SVG viewport. A single unit in the new viewport coordinate system and the new user coordinate system are the same size as a single unit in the current user coordinate system for the element establishing the SVG viewport.

Here is an example:

<?xml version="1.0" standalone="no"?>
<svg width="4in" height="3in"
     xmlns="http://www.w3.org/2000/svg">
  <desc>This SVG drawing embeds another one,
    thus establishing a new SVG viewport
  </desc>
  <!-- The following statement establishing a new SVG viewport
       and renders SVG drawing B into that SVG viewport -->
  <svg x="25%" y="25%" width="50%" height="50%">
     <!-- drawing B goes here -->
  </svg>
</svg>

For an extensive example of creating new SVG viewports, see Example PreserveAspectRatio.

The following elements establish new SVG viewports:

For historical reasons, the pattern and marker elements do not create a new viewport, despite accepting a viewBox attribute. Neither do the clipPath or mask elements. Percentage lengths within the content of these elements are not proportional to the dimensions of the graphical effect region.

The foreignObject element establishes a new CSS containing block for its child content. The same is true for a video, audio, or canvas element when its fallback content is being rendered. This has some effects similar to a new viewport, resetting the scope of layout for child content. However, in order to render SVG elements that are descendents of foreignObject, a new svg element must establish an SVG document fragment and SVG viewport.

An image or iframe element creates a new document viewport for the referenced document. If the referenced document is a SVG file, it will of course establish its own SVG viewport.

Whether a new SVG viewport also establishes a new additional clipping path is determined by the value of the overflow property on the element that establishes the new SVG viewport.

8.9. Units

SVG follows the description and definition of common values and units from the CSS Values and Units Module [css-values] for attributes, presentation attributes and CSS properties. Each attribute and property must specify the used component value type. Subsequent or extending specifications published by the CSS WG or SVG WG may extend basic data types or add new data types.

For <percentage> values that are defined to be relative to the size of SVG viewport:

Example Units below illustrates some of the processing rules for different types of units.

<?xml version="1.0" standalone="no"?>
<svg width="400px" height="200px" viewBox="0 0 4000 2000"
     xmlns="http://www.w3.org/2000/svg">
  <title>Example Units</title>
  <desc>Illustrates various units options</desc>

  <!-- Frame the picture -->
  <rect x="5" y="5" width="3990" height="1990" 
        fill="none" stroke="blue" stroke-width="10"/>

  <g fill="blue" stroke="red" font-family="Verdana" font-size="150">
    <!-- Absolute unit specifiers -->
    <g transform="translate(400,0)">
      <text x="-50" y="300" fill="black" stroke="none">Abs. units:</text>
      <rect x="0" y="400" width="4in" height="2in" stroke-width=".4in"/>
      <rect x="0" y="750" width="384" height="192" stroke-width="38.4"/>
      <g transform="scale(2)">
        <rect x="0" y="600" width="4in" height="2in" stroke-width=".4in"/>
      </g>
    </g>

    <!-- Relative unit specifiers -->
    <g transform="translate(1600,0)">
      <text x="-50" y="300" fill="black" stroke="none">Rel. units:</text>
      <rect x="0" y="400" width="2.5em" height="1.25em" stroke-width=".25em"/>
      <rect x="0" y="750" width="375" height="187.5" stroke-width="37.5"/>
      <g transform="scale(2)">
        <rect x="0" y="600" width="2.5em" height="1.25em" stroke-width=".25em"/>
      </g>
    </g>

    <!-- Percentages -->
    <g transform="translate(2800,0)">
      <text x="-50" y="300" fill="black" stroke="none">Percentages:</text>
      <rect x="0" y="400" width="10%" height="10%" stroke-width="1%"/>
      <rect x="0" y="750" width="400" height="200" stroke-width="31.62"/>
      <g transform="scale(2)">
        <rect x="0" y="600" width="10%" height="10%" stroke-width="1%"/>
      </g>
    </g>
  </g>
</svg>
Example Units — demonstrate available options

Example Units

The three rectangles on the left demonstrate the use of one of the absolute unit identifiers, the "in" unit (inch). CSS defines 1 inch to be equal to 96 pixels. Therefore, the topmost rectangle, which is specified in inches, is exactly the same size as the middle rectangle, which is specified in user units such that there are 96 user units for each corresponding inch in the topmost rectangle. The bottom rectangle of the group illustrates what happens when values specified in inches are scaled.

The three rectangles in the middle demonstrate the use of one of the relative unit identifiers, the "em" unit. Because the font-size property has been set to 150 on the outermost g element, each "em" unit is equal to 150 user units. The topmost rectangle, which is specified in "em" units, is exactly the same size as the middle rectangle, which is specified in user units such that there are 150 user units for each corresponding "em" unit in the topmost rectangle. The bottom rectangle of the group illustrates what happens when values specified in "em" units are scaled.

The three rectangles on the right demonstrate the use of percentages. Note that the width and height of the SVG viewport in the user coordinate system for the SVG viewport element (in this case, the outermost svg element) are 4000 and 2000, respectively, because processing the viewBox attribute results in a transformed user coordinate system. The topmost rectangle, which is specified in percentage units, is exactly the same size as the middle rectangle, which is specified in equivalent user units. In particular, note that the stroke-width property in the middle rectangle is set to 1% of the sqrt((actual-width)**2 + (actual-height)**2) / sqrt(2), which in this case is .01*sqrt(4000*4000+2000*2000)/sqrt(2), or 31.62. The bottom rectangle of the group illustrates what happens when values specified in percentage units are scaled.

8.10. Bounding boxes

bounding box

The bounding box (or "bbox") of an element is the tightest fitting rectangle aligned with the axes of that element's user coordinate system that entirely encloses it and its descendants.

Three kinds of bounding boxes can be computed for an element:

  1. The object bounding box is the bounding box that contains only an element's geometric shape. For basic shapes, this is the area that is filled. Unless otherwise specified, this is what is meant by the unqualified term "bounding box".
  2. The stroke bounding box is the bounding box that contains an element's geometric shape and its stroke shape.
  3. The decorated bounding box is the bounding box that contains an element's geometric shape, its stroke shape and its markers.

Note that the values of the opacity, visibility, fill, fill-opacity, fill-rule, stroke-dasharray and stroke-dashoffset properties on an element have no effect on the bounding box of an element.

For curved shapes, the bounding box must enclose all portions of the shape along the edge, not just end points. Note that control points for a curve which are not defined as lying along the line of the resulting curve (e.g., the second coordinate pair of a Cubic Bézier command) must not contribute to the dimensions of the bounding box (though those points may fall within the area of the bounding box, if they lie within the shape itself, or along or close to the curve). For example, control points of a curve that are at a further distance than the curve edge, from the non-enclosing side of the curve edge, must be excluded from the bounding box.

Image showing the object bounding box of a quadratic Bézier curve.

The path 'M20,50 L35,100 H120 V50 Q70,10 20,50' is shown in light blue. On the left, a correct object bounding box of the path is shown. Note that it does not include the top-most control point of the curve, but it does include all of the blue shape, even the parts that lie outside of the convex hull of the control points.

Even if an element is not in the rendering tree – due to it being 'display: none', within a defs element, not usually rendered like a symbol element or not currently present in the document tree – it still has a bounding box. A call to getBBox on the element will return the same rectangle as if the element were rendered. However, an element that is not in the rendering tree does not contribute to the bounding box of any ancestor element.

The following example defines a number of elements. The expected object bounding box for each element with an ID is shown below.

<svg xmlns="http://www.w3.org/2000/svg">

  <title>Bounding Box Calculation</title>
  <desc>Examples of elements with different bounding box results based on context.</desc>

  <defs id="defs-1">
     <rect id="rect-1" x="20" y="20" width="40" height="40" fill="blue" />
  </defs>

  <g id="group-1">
    <use id="use-1" href="#rect-1" x="10" y="10" />

    <g id="group-2" display="none">
      <rect id="rect-2" x="10" y="10" width="100" height="100" fill="red" />
    </g>
  </g>
</svg>
Element ID Bounding Box Result
"defs-1" {0, 0, 0, 0}
"rect-1" {20, 20, 40, 40}
"group-1" {30, 30, 40, 40}
"use-1" {30, 30, 40, 40}
"group-2" {10, 10, 100, 100}
"rect-2" {10, 10, 100, 100}

For text content elements, for the purposes of the bounding box calculation, each glyph must be treated as a separate graphics element. The calculations must assume that all glyphs occupy the full glyph cell. The full glyph cell must have width equal to the horizontal advance and height equal to the EM box for horizontal text. For vertical text that is typeset sideways, the full glyph cell must have width equal to the EM box and height equal to the horizontal advance. For other vertical text, the full glyph cell must have width equal to the EM box and height equal to the vertical advance, or height equal to the height of the EM box if no vertical advance is defined in the font. For example, for horizontal text, the calculations must assume that each glyph extends vertically to the full ascent and descent values for the font.

Because declarative or scripted animation can change the shape, size, and position of an element, the bounding box is mutable. Thus, the bounding box for an element shall reflect the current values for the element at the snapshot in time at which the bounding box is requested, whether through a script call or as part of a declarative or linking syntax.

An element which has zero width, zero height, or both (such as a vertical or horizontal line, or a rect element with a zero width or height) still has a bounding box, with a positive value for the positive dimension, or with '0' for both the width and height if no positive dimension is specified. Similarly, subpaths segments of a path element with zero width and height must be included in that element's geometry for the sake of the bounding box.

An element with no position specified (such as a path element with a value of none for the d property) is positioned at the point (0,0) for the purposes of calculating a bounding box.

Note that elements whose DOM object does not derive from SVGGraphicsElement (such as gradient elements) do not have a bounding box, and thus have no interface to request a bounding box.

Elements in the rendering tree which reference unresolved resources shall still have a bounding box, defined by the position and dimensions specified in their attributes, or by the initial value for those attributes if no values are supplied. For example, the element <use href="#bad" x="10" y="10"/> would have a bounding box with an x and y of 10 and a width and height of 0.

The following algorithm defines how to compute a bounding box for a given element. The inputs to the algorithm are:

The algorithm to compute the bounding box is as follows, depending on the type of element:

a shape
a text content element
an a element within a text content element
  1. Let box be a rectangle initialized to (0, 0, 0, 0).
  2. Let fill-shape be the equivalent path of element if it is a shape, or a shape that includes each of the glyph cells corresponding to the text within the elements otherwise.
  3. If fill is true, then set box to the tightest rectangle in the coordinate system space that contains fill-shape.

    The values of the fill, fill-opacity and fill-rule properties do not affect fill-shape.

  4. If stroke is true and the element's stroke is anything other than none, then set box to be the union of box and the tightest rectangle in coordinate system space that contains the stroke shape of the element, with the assumption that the element has no dash pattern.

    The values of the stroke-opacity, stroke-dasharray and stroke-dashoffset do not affect the calculation of the stroke shape.

  5. If markers is true, then for each marker marker rendered on the element:
    1. For each descendant graphics element child of the marker element that defines marker's content:
      1. If child has an ancestor element within the marker that is 'display: none', has a failing conditional processing attribute, or is not an a, g, svg or switch element, then continue to the next descendant graphics element.
      2. Otherwise, set box to be the union of box and the result of invoking the algorithm to compute a bounding box with child as the element, space as the target coordinate space, true for fill, stroke and markers, and clipped for clipped.
  6. If clipped is true and the value of clip-path on element is not none, then set box to be the tightest rectangle in coordinate system space that contains the intersection of box and the clipping path.
  7. Return box.
a container element
use
  1. Let box be a rectangle initialized to (0, 0, 0, 0).
  2. Let parent be the container element if it is one, or the root of the use element's shadow tree otherwise.
  3. For each descendant graphics element child of parent:
    1. If child is not rendered then continue to the next descendant graphics element.
    2. Otherwise, set box to be the union of box and the result of invoking the algorithm to compute a bounding box with child as the element and the same values for space, fill, stroke, markers and clipped as the corresponding algorithm input values.
  4. If clipped is true:
    • If the value of clip-path on element is not none, then set box to be the tightest rectangle in coordinate system space that contains the intersection of box and the clipping path.
    • If the overflow property applies to the element and does not have a value of visible, then set box to be the tightest rectangle in coordinate system space that contains the intersection of box and the element's overflow bounds.
    • If the clip property applies to the element and does not have a value of auto, then set box to be the tightest rectangle in coordinate system space that contains the intersection of box and the rectangle specified by clip.
  5. Return box.
canvas
foreignObject
iframe
image
video
  1. Let box be the tightest rectangle in coordinate space space that contains the positioning rectangle defined by the ‘x’, ‘y’, ‘width’ and ‘height’ geometric properties of the element.

    The fill, stroke and markers input arguments to this algorithm do not affect the bounding box returned for these elements.

  2. If clipped is true and the value of clip-path on element is not none, then set box to be the tightest rectangle in coordinate system space that contains the intersection of box and the clipping path.
  3. Return box.

The union box with a value of (0, 0, 0, 0) and an empty shape is box.

The object bounding box, stroke bounding box or decorated bounding box of an element is the result of invoking the bounding box computation algorithm above with the following arguments: element is the element itself; space is the element's user coordinate system; fill is true; stroke is true if we are computing the stroke bounding box or decorated bounding box, and false othwerise; markers is true if we are computing the decorated bounding box, and false otherwise; and clipped is false.

8.11. Object bounding box units

The following elements offer the option of expressing coordinate values and lengths as fractions (and, in some cases, percentages) of the object bounding box, by setting a specified attribute to 'objectBoundingBox' on the given element:

Element Attribute Effect
linearGradient gradientUnits Indicates that the attributes which specify the gradient vector (x1, y1, x2, y2) represent fractions or percentages of the bounding box of the element to which the gradient is applied.
radialGradient gradientUnits Indicates that the attributes which specify the center (cx, cy), the radius (r) and focus (fx, fy) represent fractions or percentages of the bounding box of the element to which the gradient is applied.
meshgradient gradientUnits Indicates that the attributes which specify the paint server mesh starting point (x, y) represent fractions or percentages and that mesh path data represents fractions of the bounding box of the element to which the mesh is applied. If the mesh is rendered inside a mesh element the current SVG viewport is used in place of a bounding box.
pattern patternUnits Indicates that the attributes which define how to tile the pattern (x, y, width, height) are established using the bounding box of the element to which the pattern is applied.
pattern patternContentUnits Indicates that the user coordinate system for the contents of the pattern is established using the bounding box of the element to which the pattern is applied.
clipPath clipPathUnits Indicates that the user coordinate system for the contents of the clipPath element is established using the bounding box of the element to which the clipping path is applied.
mask maskUnits Indicates that the attributes which define the masking region (x, y, width, height) is established using the bounding box of the element to which the mask is applied.
mask maskContentUnits Indicates that the user coordinate system for the contents of the mask element are established using the bounding box of the element to which the mask is applied.
filter filterUnits Indicates that the attributes which define the filter effects region (x, y, width, height) represent fractions or percentages of the bounding box of the element to which the filter is applied.
filter primitiveUnits Indicates that the various length values within the filter primitives represent fractions or percentages of the bounding box of the element to which the filter is applied.

In the discussion that follows, the term applicable element is the element to which the given effect applies. For gradients and patterns, the applicable element is the graphics element which has its fill or stroke property referencing the given gradient or pattern. (For special rules concerning text elements, see the discussion of object bounding box units and text elements.) For clipping paths, masks and filters, the applicable element can be either a container element or a graphics element.

When keyword objectBoundingBox is used, then the effect is as if a supplemental transformation matrix were inserted into the list of nested transformation matrices to create a new user coordinate system.

First, the (minx,miny) and (maxx,maxy) coordinates are determined by the extends of the object bounding box of the applicable element.

Then, coordinate (0,0) in the new user coordinate system is mapped to the (minx,miny) corner of the tight bounding box within the user coordinate system of the applicable element and coordinate (1,1) in the new user coordinate system is mapped to the (maxx,maxy) corner of the tight bounding box of the applicable element. In most situations, the following transformation matrix produces the correct effect:

[ (maxx-minx) 0 0 (maxy-miny) minx miny ]

When percentages are used with attributes that define the gradient vector, the pattern tile, the filter region or the masking region, a percentage represents the same value as the corresponding decimal value (e.g., 50% means the same as 0.5). If percentages are used within the content of a pattern, clipPath, mask or filter element, these values are treated according to the processing rules for percentages as defined in Units.

Any numeric value can be specified for values expressed as a fraction or percentage of object bounding box units. In particular, fractions less are zero or greater than one and percentages less than 0% or greater than 100% can be specified.

Keyword objectBoundingBox should not be used when the geometry of the applicable element has no width or no height, such as the case of a horizontal or vertical line, even when the line has actual thickness when viewed due to having a non-zero stroke width since stroke width is ignored for bounding box calculations. When the geometry of the applicable element has no width or height and objectBoundingBox is specified, then the given effect (e.g., a gradient or a filter) will be ignored.

8.12. Intrinsic sizing properties of SVG content

To enable inclusion of SVG in host documents formatted with CSS, a concrete object size must be calculated. The concrete object size must be calculated using the Default Sizing Algorithm defined in CSS Images 3 [css3-images], with the following inputs:

The specified size must be determined from the used values for the width and height sizing properties of the svg element.

The intrinsic dimensions must also be determined from the width and height sizing properties. If either width or height are not specified, the used value is the initial value 'auto'. 'auto' and percentage lengths must not be used to determine an intrinsic width or intrinsic height.

With bitmap image formats, the intrinsic dimensions are fixed in the image file, and the specified size is defined in the host document as needed to scale the image. SVG, being inherently scalable, adapts the intrinsic width and intrinsic height to be the width and height of the specified size. Therefore, when specified as a length, the width and height sizing properties of the svg element control the intrinsic dimensions of the SVG image and the specified size that is used when placing the SVG image in a host document.

The intrinsic aspect ratio must be calculated using the following algorithm. If the algorithm returns null, then there is no intrinsic aspect ratio.

  1. If the width and height sizing properties on the svg element are both absolute values:
    1. return width / height
  2. If an SVG View is active:
    1. let viewbox be the viewbox defined by the active SVG View
    2. return viewbox.width / viewbox.height
  3. If the viewBox on the svg element is correctly specified:
    1. let viewbox be the viewbox defined by the viewBox attribute on the svg element
    2. return viewbox.width / viewbox.height
  4. return null

The behaviour defined in this section is specific to CSS, but may be adapted to other host contexts. In all host contexts, the intrinsic aspect ratio, where available, must be respected when sizing the SVG viewport.

Examples:

Example: Intrinsic Aspect Ratio 1
<svg xmlns="http://www.w3.org/2000/svg"
     width="10cm" height="5cm">
  ...
</svg>

In this example the intrinsic aspect ratio of the SVG viewport is 2:1. The intrinsic width is 10cm and the intrinsic height is 5cm.

Example: Intrinsic Aspect Ratio 2
<svg xmlns="http://www.w3.org/2000/svg"
     width="100%" height="50%" viewBox="0 0 200 200">
  ...
</svg>

In this example the intrinsic aspect ratio of the outermost SVG viewport is 1:1. An aspect ratio calculation in this case allows embedding in an object within a containing block that is only constrained in one direction.

Example: Intrinsic Aspect Ratio 3
<svg xmlns="http://www.w3.org/2000/svg"
     width="10cm" viewBox="0 0 200 200">
  ...
</svg>

In this case the intrinsic aspect ratio is 1:1.

Example: Intrinsic Aspect Ratio 4
<svg xmlns="http://www.w3.org/2000/svg"
     width="75%" height="10cm" viewBox="0 0 200 200">
  ...
</svg>

In this example, the intrinsic aspect ratio is 1:1.

Add more examples for the new auto value? E.g some of the examples provided by David Vest.

8.13. Vector effects

SVG 2 Requirement: SVG 2 will have constrained transformations based on SVG 1.2 Tiny.
Resolution: Add vector effects extension proposal to SVG 2 specification.
Purpose: To include non-scaling features (non-scaling part of the object, and non-scaling entire object
Owner: Satoru Takagi (ACTION-3619)

Sometimes it is of interest to let the outline of an object keep its original width or to let the position of an object fix no matter which transforms are applied to it. For example, in a map with a 2px wide line representing roads it is of interest to keep the roads 2px wide even when the user zooms into the map, or introductory notes on the graphic chart in which panning is possible.

To offer such effects regarding special coordinate transformations and graphic drawings, SVG Tiny 1.2 introduced the vector-effect property. Although SVG Tiny 1.2 introduced only non-scaling stroke behavior, this version introduces a number of additional effects. Furthermore, since these effects can be specified in combination, they show more various effects. And, future versions of the SVG language will allow for more powerful vector effects through this property.

Values of vector-effect other than non-scaling-stroke and none are at risk of being dropped from SVG 2 due to a lack of implementations. Feedback from implementers is requested, regarding the practicality of implementing them as currently specified, during the implementation period.

Name: vector-effect
Value: none | [ non-scaling-stroke | non-scaling-size | non-rotation | fixed-position ]+ [ viewport | screen ]?
Initial: none
Applies to: graphics elements and use
Inherited: no
Percentages: N/A
Media: visual
Computed value: as specified
Animatable: yes
none
Specifies that no vector effect shall be applied, i.e. the default rendering behaviour from SVG 1.1 is used which is to first fill the geometry of a shape with a specified paint, then stroke the outline with a specified paint.
non-scaling-stroke
Please refer to this description of vector effect on painting.
non-scaling-size
Specifies special local coordinate system toward this element and its descendant by constrained transformations with the following characteristics. The scale of the local coordinate system do not change in spite of change of CTMs from a host coordinate space. However, it does not specify the suppression of rotation and skew. Also, it does not specify the fixation of placement of local coordinate system. Since non-scaling-size suppresses scaling of local coordinate system, it also has the characteristic of non-scaling-stroke. The transformation formula and the example behavior are indicated to the following chapter.
non-rotation
Specifies special local coordinate system toward this element and its descendant by constrained transformations with the following characteristics. The rotation and skew of the local coordinate system is suppressd in spite of change of CTMs from a host coordinate space. However, it does not specify the suppression of scaling. Also, it does not specify the fixation of placement of local coordinate system. The transformation formula and the example behavior are indicated to the following chapter.
fixed-position
Specifies special local coordinate system toward this element and its descendant by constrained transformations with the following characteristics. The placement of local coordinate system is fixed in spite of change of CTMs from a host coordinate space. However, it does not specify the suppression of rotation, skew and scaling. When the element that has fixed-position effect and also has transform property, that property is consumed for this effect. The shift components e and f of matrix of transform property are used to transfer the origin of fixed local coordinate system. The transformation formula and the example behavior are indicated to the following chapter.

These values can be enumerated. Thereby, the effect which has these characteristics simultaneously can be specified.

The following two values assists the above-mentioned values. They show the host coordinate space of constrained transformations. Especially it has effective for the element belonging to nested viewport coordinate system such as nested contents or nested svg elements. An initial value in case it is not specified is viewport.

viewport
Specifies immediate viewport coordinate system as the host coordinate space. When that element belongs to nested viewport coordinate system, vector effects are applied toward viewport coordinate system to which that element belongs directly. That is, that vector effect is not effective for change of CTM on ancestral viewport coordinate system.
screen
It specifies the coordinate system of content which under the immediate control of user agent. So to speak, it is "scrren" which user agent has. ("screen coordinate space" in SVGT1.2) Even if that element belongs to nested viewport coordinate system, that vector effect is always effective for change of CTM of the any hierarchy. If the SVG implementation is part of a user agent which supports CSS compatible px units, it is a coordinate system on CSS pixel of rootmost content. Generally, the pixel (or dot) of a device and pixel of CSS are not always equal by influences of the zoom function which user agent itself has, and variation of dpi. (see resolution [CSS Values and Units Module Level 3]) Accordingly, this value does not specify constrained transformations toward the such a device coordinate system.

Note: Future versions of SVG may allow ways to specify the device coordinate system.

8.13.1. Computing the vector effects

This section shows the list of transformation formulas regarding combinations of the values for clarification of the behavior of vector effects excluding non-scaling-stroke which has clear implications.

The vector-effect property has no effect on transformations performed in a 3d rendering context.

The normal coordinate transformation formula from local coordinate system to viewport coordinate system is as follows.

x viewport y viewport 1 = CTM x userspace y userspace 1 CTM = a ctm c ctm e ctm b ctm d ctm f ctm 0 0 1
<circle vector-effect="veValue" transform="translate(xo yo)" cx="xf" cy="yf" r=".."/>

When the vector-effect is added to an element like the above, the transformation formula for user coordinate to the device coordinate changes as follows. Here, xf and yf are user coordinate of the corresponding element and its descendant. And, xo and yo are matrix element e and f of the transform attribute which the corresponding element has. In addition, |det(CTM)| is absolute value of the determinants of CTM. When this value becomes 0 and non-scaling-size is appointed, vector-effect becomes invalidity namely none.

det CTM = a ctm d ctm - b ctm c ctm
veValue Formula
non-scaling-size
x viewport y viewport 1 = CTM 0 0 1 + CTM det CTM 1 0 0 0 1 0 0 0 0 x f y f 1
non-rotation
x viewport y viewport 1 = CTM 0 0 1 + det CTM 1 0 0 0 1 0 0 0 0 x f y f 1
non-scaling-size non-rotation
x viewport y viewport 1 = CTM 0 0 1 + 1 0 0 0 1 0 0 0 0 x f y f 1
fixed-position
x viewport y viewport 1 = x o y o 1 + CTM 1 0 0 0 1 0 0 0 0 x f y f 1
fixed-position non-scaling-size
x viewport y viewport 1 = x o y o 1 + CTM det CTM 1 0 0 0 1 0 0 0 0 x f y f 1
fixed-position non-rotation
x viewport y viewport 1 = x o y o 1 + det CTM 1 0 0 0 1 0 0 0 0 x f y f 1
fixed-position non-scaling-size non-rotation
x viewport y viewport 1 = x o y o 1 + 1 0 0 0 1 0 0 0 0 x f y f 1

8.13.2. Computing the vector effects for nested viewport coordinate systems

Below is normal coordinate transformation formula for nested viewport coordinate systems without vector effects. xviewport(UA) and yviewport(UA) are coordinates which under the immediate control of user agent. CTMthis is CTM for the transformation matrix from local coordinate system of an target graphic to viewport coordinate system to which it belongs. CTMparent is CTM for the transformation matrix from aforementioned viewport coordinate system to viewport coordinate system of the parent of that. And, CTMroot is CTM for rootmost viewport coordinate system (UA).

x viewport(UA) y viewport(UA) 1 = CTM root ... CTM parent CTM this x userspace y userspace 1

When applying seven formulas of the preceding section to nested viewport coordinate systems, the application way of those formulas changes as follows by whether viewport or screen is specified as the additional value of vector-effect.

When viewport value is specified, user agent computes coordinates combining either of seven formulas of the preceding chapter, and the following formulas.

x viewport ( UA ) y viewport ( UA ) 1 = CTM root ... CTM parent x viewport y viewport 1 CTM = CTM this

When screen value is specified, user agent computes coordinates combining either of seven formulas of the preceding chapter, and the following formulas.

x viewport ( UA ) y viewport ( UA ) 1 = x viewport y viewport 1 CTM = CTM root ... CTM parent CTM this

8.13.3. Examples of vector effects

Below is an example of the non-scaling-stroke vector-effect.

<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg"
     width="6cm" height="4cm" viewBox="0 0 600 400" 
     viewport-fill="rgb(255,150,200)">

  <desc>Example non-scaling stroke</desc>
  <rect x="1" y="1" width="598" height="398" fill="none" stroke="black"/>
  
  <g transform="scale(9,1)">
    <line stroke="black" stroke-width="5" x1="10" y1="50" x2="10" y2="350"/>
    <line vector-effect="non-scaling-stroke" stroke="black" stroke-width="5" 
        x1="32" y1="50" x2="32" y2="350"/>
    <line vector-effect="none" stroke="black" stroke-width="5" 
        x1="55" y1="50" x2="55" y2="350"/>
  </g>

</svg>

Below is an example of the none vector-effect (no vector effect).

Before changing CTMAfter changing CTM
Image showing none vector effect Image showing none vector effect

Source code

<svg xmlns="http://www.w3.org/2000/svg" viewBox="-50,-50,500,500" height="500" width="500">

  <rect x="-50" y="-50" width="500" height="500" stroke="orange" stroke-width="3" fill="none"/>

  <!-- Nested local coordinate system is transformed by this transform attribute -->
  <g transform="matrix(2.1169438081370817,0.3576047954311102,-0.3576047954311102,1.4700998667618626,0,0)
                translate(-50,-50)">
    <svg viewBox="-50,-50,500,500" height="500" width="500">
      <!-- Graph paper on the this svg's base local coordinate system -->
      <g stroke="green" stroke-width="1" fill="none">
        <circle cx="0" cy="0" r="10"/>
        <circle cx="150" cy="150" r="7"/>
        <path fill="green" stroke="none" d="M0,-3 L30,-3 25,-10 50,0 25,10 30,3 0,3z"/>

        <line x1="-100" y1="-100" x2="600" y2="-100" stroke-dasharray="5,5"/>
        <line x1="-100" y1="000" x2="600" y2="000"/>
        <line x1="-100" y1="100" x2="600" y2="100" stroke-dasharray="5,5"/>
        <line x1="-100" y1="200" x2="600" y2="200" stroke-dasharray="5,5"/>
        <line x1="-100" y1="300" x2="600" y2="300" stroke-dasharray="5,5"/>
        <line x1="-100" y1="400" x2="600" y2="400" stroke-dasharray="5,5"/>
        <line x1="-100" y1="500" x2="600" y2="500" stroke-dasharray="5,5"/>

        <line y1="-100" x1="-100" y2="600" x2="-100" stroke-dasharray="5,5"/>
        <line y1="-100" x1="000" y2="600" x2="000"/>
        <line y1="-100" x1="100" y2="600" x2="100" stroke-dasharray="5,5"/>
        <line y1="-100" x1="200" y2="600" x2="200" stroke-dasharray="5,5"/>
        <line y1="-100" x1="300" y2="600" x2="300" stroke-dasharray="5,5"/>
        <line y1="-100" x1="400" y2="600" x2="400" stroke-dasharray="5,5"/>
        <line y1="-100" x1="500" y2="600" x2="500" stroke-dasharray="5,5"/>
      </g>

      <!-- Figure having vector effect -->
      <!-- A thick red right arrow and small rectangle on this figure's nested
           local coordinate system origin -->
      <path id="ve" vector-effect="none"
            stroke="red" stroke-width="3" fill="none"
            transform="matrix(1,0,0,1,150,150)"
            d="M-50,-50 L50,-50 50,-100 150,0 50,100 50,50 -50,50 -50,-50z M5 0 L0 -5 -5 0 0 5z"/>
    </svg>
  </g>
</svg>

Below is an example of the non-scaling-size.

Before changing CTMAfter changing CTM
Image showing appearance before the effect of the vector effect showing up Image showing non-scaling-size vector effect
<path id="ve" vector-effect="non-scaling-size"
      stroke="red" stroke-width="3" fill="none"
      transform="matrix(1,0,0,1,150,150)"
      d="M-50,-50 L50,-50 50,-100 150,0 50,100 50,50 -50,50 -50,-50z M5 0 L0 -5 -5 0 0 5z"/>

Below is an example of the non-rotation.

Before changing CTMAfter changing CTM
Image showing appearance before the effect of the vector effect showing up Image showing non-rotation vector effect
<path id="ve" vector-effect="non-rotation"
      stroke="red" stroke-width="3" fill="none"
      transform="matrix(1,0,0,1,150,150)"
      d="M-50,-50 L50,-50 50,-100 150,0 50,100 50,50 -50,50 -50,-50z M5 0 L0 -5 -5 0 0 5z"/>

Below is an example of the non-scaling-size non-rotation.

Before changing CTMAfter changing CTM
Image showing appearance before the effect of the vector effect showing up Image showing non-scaling-size non-rotation vector effect
<path id="ve" vector-effect="non-scaling-size non-rotation"
      stroke="red" stroke-width="3" fill="none"
      transform="matrix(1,0,0,1,150,150)"
      d="M-50,-50 L50,-50 50,-100 150,0 50,100 50,50 -50,50 -50,-50z M5 0 L0 -5 -5 0 0 5z"/>

Below is an example of the fixed-position.

Before changing CTMAfter changing CTM
Image showing appearance before the effect of the vector effect showing up Image showing fixed-position vector effect
<path id="ve" vector-effect="fixed-position"
      stroke="red" stroke-width="3" fill="none"
      transform="matrix(1,0,0,1,150,150)"
      d="M-50,-50 L50,-50 50,-100 150,0 50,100 50,50 -50,50 -50,-50z M5 0 L0 -5 -5 0 0 5z"/>

Below is an example of the non-scaling-size fixed-position.

Before changing CTMAfter changing CTM
Image showing appearance before the effect of the vector effect showing up Image showing non-scaling-size fixed-position vector effect
<path id="ve" vector-effect="non-scaling-size fixed-position"
      stroke="red" stroke-width="3" fill="none"
      transform="matrix(1,0,0,1,150,150)"
      d="M-50,-50 L50,-50 50,-100 150,0 50,100 50,50 -50,50 -50,-50z M5 0 L0 -5 -5 0 0 5z"/>

Below is an example of the non-rotation fixed-position.

Before changing CTMAfter changing CTM
Image showing appearance before the effect of the vector effect showing up Image showing non-rotation fixed-position vector effect
<path id="ve" vector-effect="non-rotation fixed-position"
      stroke="red" stroke-width="3" fill="none"
      transform="matrix(1,0,0,1,150,150)"
      d="M-50,-50 L50,-50 50,-100 150,0 50,100 50,50 -50,50 -50,-50z M5 0 L0 -5 -5 0 0 5z"/>

Below is an example of the non-scaling-size non-rotation fixed-position.

Before changing CTMAfter changing CTM
Image showing appearance before the effect of the vector effect showing up Image showing non-scaling-size non-rotation fixed-position vector effect
<path id="ve" vector-effect="non-scaling-size non-rotation fixed-position"
      stroke="red" stroke-width="3" fill="none"
      transform="matrix(1,0,0,1,150,150)"
      d="M-50,-50 L50,-50 50,-100 150,0 50,100 50,50 -50,50 -50,-50z M5 0 L0 -5 -5 0 0 5z"/>

8.14. DOM interfaces

8.14.1. Interface SVGTransform

The SVGTransform interface is used to represent <transform-function> values that appear in the transform property and its presentation attributes ‘transform’, gradientTransform and patternTransform. An SVGTransform represents a single component in a transform list, such as a single scale(…) or matrix(…) value.

An SVGTransform object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown, as described below.

An SVGTransform object can be associated with a particular element. The associated element is used to determine which element's ‘transform’ presentation attribute to update if the object reflects that attribute. Unless otherwise described, an SVGTransform object is not associated with any element.

Every SVGTransform object operates in one of two modes. It can:

  1. reflect an element of a presentation attribute value (being exposed through the methods on the baseVal member of an SVGAnimatedTransformList),
  2. be detached, which is the case for SVGTransform objects created with createSVGTransform and createSVGTransformFromMatrix.

An SVGTransform object maintains an internal <transform-function> value, which is called its value. It also maintains a DOMMatrix object, which is called its matrix object, which is the object returned from the matrix IDL attribute. An SVGTransform object's matrix object is always kept synchronized with it its value.

interface SVGTransform {

  // Transform Types
  const unsigned short SVG_TRANSFORM_UNKNOWN = 0;
  const unsigned short SVG_TRANSFORM_MATRIX = 1;
  const unsigned short SVG_TRANSFORM_TRANSLATE = 2;
  const unsigned short SVG_TRANSFORM_SCALE = 3;
  const unsigned short SVG_TRANSFORM_ROTATE = 4;
  const unsigned short SVG_TRANSFORM_SKEWX = 5;
  const unsigned short SVG_TRANSFORM_SKEWY = 6;

  readonly attribute unsigned short type;
  [SameObject] readonly attribute DOMMatrix matrix;
  readonly attribute float angle;

  void setMatrix(DOMMatrixReadOnly matrix);
  void setTranslate(float tx, float ty);
  void setScale(float sx, float sy);
  void setRotate(float angle, float cx, float cy);
  void setSkewX(float angle);
  void setSkewY(float angle);
};

The numeric transform type constants defined on SVGTransform are used to represent the type of an SVGTransform's value. Their meanings are as follows:

ConstantMeaning
SVG_TRANSFORM_MATRIXA matrix(…) value.
SVG_TRANSFORM_TRANSLATEA translate(…) value.
SVG_TRANSFORM_SCALEA scale(…) value.
SVG_TRANSFORM_ROTATEA rotate(…) value.
SVG_TRANSFORM_SKEWXA skewX(…) value.
SVG_TRANSFORM_SKEWYA skewY(…) value.
SVG_TRANSFORM_UNKNOWNSome other type of value.

The use of numeric transform type constants is an anti-pattern and new constant values will not be introduced for any transform types supported by SVGTransform. If other types of transforms are supported and used, the SVGTransform uses the SVG_TRANSFORM_UNKNOWN type. See below for details on how the other properties of an SVGTransform operate with these types of transforms.

The type IDL attribute represents the type of transform item that the SVGTransform's value is. On getting type, the following steps are run:

  1. If the SVGTransform's value is a matrix(…), translate(…), scale(…), rotate(…), skewX(…) or skewY(…) function, then return the corresponding constant value from the transform type table above.
  2. Otherwise, return SVG_TRANSFORM_UNKNOWN.

    For example, for a scaleX(…) or translate3d(…) transform, SVG_TRANSFORM_UNKNOWN would be returned.

The matrix IDL attribute represents the transform as a 4x4 homogeneous matrix, and on getting returns the SVGTransform's matrix object. When the matrix object is first created, its values are set to match the SVGTransform's transform function value, and is set to reflects the SVGTransform.

See the CSS Transforms specification for a description of how the different transform function types correspond to particular matrix values.

The angle IDL attribute represents the angle parameter of a rotate(…), skewX(…) or skewY(…) transform function. On getting, the following steps are run:

  1. If the SVGTransform object's value is a rotate(…), skewX(…) or skewY(…) function, return its angle argument in degrees.
  2. Otherwise, return 0.

The setMatrix method is used to set the SVGTransform to a given matrix value. When setMatrix(matrix) is called, the following steps are run:

  1. If the SVGTransform object is read only, then throw a NoModificationAllowedError.
  2. If matrix would return true from its is2d method, then set the SVGTransform object's value to a matrix(…) value that represents the same matrix as matrix.
  3. Otherwise, set the SVGTransform object's value to a matrix3d(…) value that represents the same matrix as matrix.
  4. Copy the matrix component values from matrix into the SVGTransform object's matrix object.
  5. If the SVGTransform object reflects an element of a presentation attribute value, then reserialize the reflected attribute.

The setTranslate, setScale, setRotate, setSkewX and setSkewY methods are used to set the SVGTransform to a new transform function value. When one of these methods is called, the following steps are run:

  1. If the SVGTransform object is read only, then throw a NoModificationAllowedError.
  2. Set the SVGTransform object's value to a new transform function value, depending on which method was called:
    setTranslate(tx, ty)
    the new transform function value is translate(tx, ty)
    setScale(sx, sy)
    the new transform function value is scale(sx, sy)
    setRotate(angle, cx, cy)
    the new transform function value is rotate(angle, cx, cy)
    setSkewX(angle)
    the new transform function value is skewX(angle)
    setSkewY(angle)
    the new transform function value is skewY(angle)
  3. Set the components of the SVGTransform object's matrix object to match the new transform function value.
  4. If the SVGTransform object reflects an element of a presentation attribute value, then reserialize the reflected attribute.

This specification imposes additional requirements on the behavior of DOMMatrix objects beyond those described in the the Geometry Interfaces specification, so that they can be used to reflect presentation attributes that take transform values.

Every DOMMatrix object operates in one of two modes. It can:

  1. reflect an SVGTransform (being exposed through the matrix IDL attribute on an SVGTransform), or
  2. be detached, which is the case for DOMMatrix objects created using their constructor or with createSVGMatrix.

A DOMMatrix can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. When assigning to any of a read only DOMMatrix's IDL attributes, or when invoking any of its mutable transform methods, a NoModificationAllowedError exception will be thrown instead of updating the internal value.

Note that this applies only to the read-write DOMMatrix interface; the DOMMatrixReadOnly interface, which is not used for reflecting transform, will already throw an exception if an attempt is made to modify it.

When assigning to any of a writable DOMMatrix's IDL attributes, or when invoking any of its mutable transform methods, the following steps are run after updating the internal matrix value:

  1. If the DOMMatrix reflects an SVGTransform, then:
    1. If the DOMMatrix would return true from its is2d method, then set the SVGTransform object's value to a matrix(…) value that represents the same matrix as the DOMMatrix.
    2. Otherwise, set the SVGTransform object's value to a matrix3d(…) value that represents the same matrix as the DOMMatrix.
    3. If the SVGTransform object reflects an element of a presentation attribute value, then reserialize the reflected attribute.

8.14.2. Interface SVGTransformList

The SVGTransformList interface is a list interface whose elements are SVGTransform objects. An SVGTransformList represents a value that the transform property can take, namely either a <transform-list> or the keyword none.

interface SVGTransformList {

  readonly attribute unsigned long length;
  readonly attribute unsigned long numberOfItems;

  void clear();
  SVGTransform initialize(SVGTransform newItem);
  getter SVGTransform getItem(unsigned long index);
  SVGTransform insertItemBefore(SVGTransform newItem, unsigned long index);
  SVGTransform replaceItem(SVGTransform newItem, unsigned long index);
  SVGTransform removeItem(unsigned long index);
  SVGTransform appendItem(SVGTransform newItem);
  setter void (unsigned long index, SVGTransform newItem);

  // Additional methods not common to other list interfaces.
  SVGTransform createSVGTransformFromMatrix(DOMMatrixReadOnly matrix);
  SVGTransform? consolidate();
};

The createSVGTransformFromMatrix method is used to create a new SVGTransform object from a matrix object. When the createSVGTransformFromMatrix(matrix) method is called, the following steps are run:

  1. Let transform be a newly created SVGTransform object that is detached.
  2. Follow the steps that would be run if the setMatrix method on transform were called, passing matrix as its argument.
  3. Return transform.

The consolidate method is used to convert the transform list into an equivalent transformation using a single transform function. When the consolidate() method is called, the following steps are run:

  1. If the SVGTransformList object is read only, then throw a NoModificationAllowedError.
  2. If the list is empty, return null.
  3. Detach and then remove all elements in the list.
  4. Let transform be a newly created SVGTransform object.
  5. Let matrix be the matrix value obtained by beginning with an identity matrix, and then post-multiplying the value of the matrix object for each SVGTransform in the list, in order.
  6. Set the components of transform's matrix object to the component values in matrix.
  7. If transform's matrix object would return true from its is2d method, then set transform's value to a matrix(…) value that represents the same matrix as the matrix object.
  8. Otherwise, set transform's value to a matrix3d(…) value that represents the same matrix as the matrix object.
  9. Attach transform to this SVGTransformList.
  10. Append transform to this list.
  11. If the list reflects a presentation attribute, then reserialize the reflected attribute.
  12. Return transform.

The behavior of all other interface members of SVGLengthList are defined in List interfaces.

8.14.3. Interface SVGAnimatedTransformList

An SVGAnimatedTransformList object is used to reflect the transform property and its corresponding presentation attribute (which, depending on the element, is ‘transform’, gradientTransform or patternTransform).

interface SVGAnimatedTransformList {
  [SameObject] readonly attribute SVGTransformList baseVal;
  [SameObject] readonly attribute SVGTransformList animVal;
};

The baseVal and animVal IDL attributes represent the value of the reflected presentation attribute. On getting baseVal or animVal, an SVGTransformList object is returned that reflects the given presentation attribute.

8.14.4. Interface SVGPreserveAspectRatio

The SVGPreserveAspectRatio interface is used to represent values for the preserveAspectRatio attribute.

An SVGPreserveAspectRatio object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown, as described below.

Every SVGPreserveAspectRatio object reflects the base value of a reflected preserveAspectRatio attribute (being exposed through the methods on the baseVal or animVal member of an SVGAnimatedPreserveAspectRatio).

interface SVGPreserveAspectRatio {

  // Alignment Types
  const unsigned short SVG_PRESERVEASPECTRATIO_UNKNOWN = 0;
  const unsigned short SVG_PRESERVEASPECTRATIO_NONE = 1;
  const unsigned short SVG_PRESERVEASPECTRATIO_XMINYMIN = 2;
  const unsigned short SVG_PRESERVEASPECTRATIO_XMIDYMIN = 3;
  const unsigned short SVG_PRESERVEASPECTRATIO_XMAXYMIN = 4;
  const unsigned short SVG_PRESERVEASPECTRATIO_XMINYMID = 5;
  const unsigned short SVG_PRESERVEASPECTRATIO_XMIDYMID = 6;
  const unsigned short SVG_PRESERVEASPECTRATIO_XMAXYMID = 7;
  const unsigned short SVG_PRESERVEASPECTRATIO_XMINYMAX = 8;
  const unsigned short SVG_PRESERVEASPECTRATIO_XMIDYMAX = 9;
  const unsigned short SVG_PRESERVEASPECTRATIO_XMAXYMAX = 10;

  // Meet-or-slice Types
  const unsigned short SVG_MEETORSLICE_UNKNOWN = 0;
  const unsigned short SVG_MEETORSLICE_MEET = 1;
  const unsigned short SVG_MEETORSLICE_SLICE = 2;

  attribute unsigned short align;
  attribute unsigned short meetOrSlice;
};

The numeric alignment type constants defined on SVGPreserveAspectRatio are used to represent the alignment keyword values that preserveAspectRatio can take. Their meanings are as follows:

ConstantMeaning
SVG_PRESERVEASPECTRATIO_NONEThe none keyword.
SVG_PRESERVEASPECTRATIO_XMINYMINThe xMinYMin keyword.
SVG_PRESERVEASPECTRATIO_XMIDYMINThe xMidYMin keyword.
SVG_PRESERVEASPECTRATIO_XMAXYMINThe xMaxYMin keyword.
SVG_PRESERVEASPECTRATIO_XMINYMIDThe xMinYMid keyword.
SVG_PRESERVEASPECTRATIO_XMIDYMIDThe xMidYMid keyword.
SVG_PRESERVEASPECTRATIO_XMAXYMIDThe xMaxYMid keyword.
SVG_PRESERVEASPECTRATIO_XMINYMAXThe xMinYMax keyword.
SVG_PRESERVEASPECTRATIO_XMIDYMAXThe xMidYMax keyword.
SVG_PRESERVEASPECTRATIO_XMAXYMAXThe xMaxYMax keyword.
SVG_PRESERVEASPECTRATIO_UNKNOWNSome other type of value.

Similarly, the numeric meet-or-slice type constants defined on SVGPreserveAspectRatio are used to represent the meet-or-slice keyword values that preserveAspectRatio can take. Their meanings are as follows:

ConstantMeaning
SVG_MEETORSLICE_MEETThe meet keyword.
SVG_MEETORSLICE_SLICEThe slice keyword.
SVG_MEETORSLICE_UNKNOWNSome other type of value.

The align IDL attribute represents the alignment keyword part of the preserveAspectRatio value. On getting, the following steps are run:

  1. Let value reflect the base value of a preserveAspectRatio attribute. value is the current non-animated value of the attribute (using the attribute's initial value if it is not present or invalid).
  2. Return the constant value as specified in the alignment constant table above for the alignment keyword in value.

On setting align, the following steps are run:

  1. If the SVGPreserveAspectRatio is read only, then throw a NoModificationAllowedError.
  2. If value is SVG_PRESERVEASPECTRATIO_UNKNOWN or does not have a corresponding entry in the alignment keyword table above, then return.
  3. Let string be the corresponding keyword in the alignment keyword table above for value.
  4. Append a single U+0020 SPACE character to string.
  5. Let meet or slice be the value that would be returned from the meetOrSlice member on this SVGPreserveAspectRatio.
  6. Append to string the corresponding keyword in the meet-or-slice keyword table above for meet or slice.
  7. Set the reflected preserveAspectRatio attribute to string.

The meetOrSlice IDL attribute represents the alignment keyword part of the preserveAspectRatio value. On getting, the following steps are run:

  1. Let value be a preserveAspectRatio value that reflects the base value of a preserveAspectRatio attribute value is the current non-animated value of the attribute.
  2. If the meet-or-slice value is not present in value, then return SVG_MEETORSLICE_MEET.
  3. Otherwise, the meet-or-slice value is present. Return the constant value as specified in the meet-or-slice constant table above for the meet-or-slice keyword in value.

On setting meetOrSlice, the following steps are run:

  1. If the SVGPreserveAspectRatio is read only, then throw a NoModificationAllowedError.
  2. If value is SVG_MEETORSLICE_UNKNOWN or does not have a corresponding entry in the meet-or-slice keyword table above, then return.
  3. Let align be the value that would be returned from the align member on this SVGPreserveAspectRatio.
  4. Let string be the corresponding keyword in the alignment keyword table above for align.
  5. Append a single U+0020 SPACE character to string.
  6. Append to string the corresponding keyword in the meet-or-slice keyword table above for value.
  7. Set the reflected preserveAspectRatio attribute to string.

8.14.5. Interface SVGAnimatedPreserveAspectRatio

An SVGAnimatedPreserveAspectRatio object is used to reflect the preserveAspectRatio attribute.

interface SVGAnimatedPreserveAspectRatio {
  [SameObject] readonly attribute SVGPreserveAspectRatio baseVal;
  [SameObject] readonly attribute SVGPreserveAspectRatio animVal;
};

The baseVal and animVal IDL attributes represent the current non-animated value of the reflected preserveAspectRatio attribute. On getting baseVal or animVal, an SVGPreserveAspectRatio object is returned that reflects the base value of the preserveAspectRatio attribute on the SVG element that the object with the reflcting IDL attribute of type SVGAnimatedPreserveAspectRatio was obtained from.


Chapter 9: Paths

9.1. Introduction

A path represents the outline of a shape which can be filled or stroked. A path can also be used as a clipping path, to describe animation, or position text. A path can be used for more than one of these functions at the same time. (See Filling, Stroking and Paint Servers, Clipping and Masking, Animation ('animateMotion'), and Text on a Path.)

A path is described using the concept of a current point. In an analogy with drawing on paper, the current point can be thought of as the location of the pen. The position of the pen can be changed, and the outline of a shape (open or closed) can be traced by dragging the pen in either straight lines or curves.

Paths represent the geometry of the outline of an object, defined in terms of moveto (set a new current point), bearing (set a new orientation), lineto (draw a straight line), curveto (draw a curve using a cubic Bézier), arc (elliptical or circular arc) and closepath (close the current shape by connecting to the last moveto) commands. Compound paths (i.e., a path with multiple subpaths) are possible to allow effects such as "donut holes" in objects.

This chapter describes the syntax, behavior and DOM interfaces for SVG paths. Various implementation notes for SVG paths can be found in ‘path’ element implementation Notes and Elliptical arc implementation notes.

A path is defined in SVG using the path element.

The basic shapes are all described in terms of what their equivalent path is, which is what their shape is as a path. (The equivalent path of a path element is simply the path itself.)

9.2. The ‘path’ element

path
Categories:
Graphics element, renderable element, shape element
Content model:
Any number of the following elements, in any order:clipPath, marker, mask, script, style
Attributes:
Geometry properties:
DOM Interfaces:

The outline of a shape for a path element is specified using the d property. See Path data below.

9.3. Path data

SVG 2 Requirement: Support turtle-graphics-like current rotation in path syntax.
Resolution: We will add a path rotation command.
Purpose: Make path rotations easier to animate and pie charts easier to draw.
Owner: Cameron (ACTION-3125)
Status: Done

9.3.1. General information about path data

A path is defined by including a path element on which the d property specifies the path data. The path data contains the moveto, bearing, lineto, curveto (both cubic and quadratic Béziers), arc and closepath instructions.

Example triangle01 specifies a path in the shape of a triangle. (The M indicates a moveto, the Ls indicate linetos, and the z indicates a closepath).

<?xml version="1.0" standalone="no"?>
<svg width="4cm" height="4cm" viewBox="0 0 400 400"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
  <title>Example triangle01- simple example of a 'path'</title>
  <desc>A path that draws a triangle</desc>
  <rect x="1" y="1" width="398" height="398"
        fill="none" stroke="blue" />
  <path d="M 100 100 L 300 100 L 200 300 z"
        fill="red" stroke="blue" stroke-width="3" />
</svg>
Example triangle01 — simple example of a 'path'

Example triangle01

View this example as SVG (SVG-enabled browsers only)

Path data can contain newline characters and thus can be broken up into multiple lines to improve readability. Newlines inside attributes in markup will be normalized to space characters while parsing.

The syntax of path data is concise in order to allow for minimal file size and efficient downloads, since many SVG files will be dominated by their path data. Some of the ways that SVG attempts to minimize the size of pat