W3C

Scalable Vector Graphics (SVG) 2

W3C Editor’s Draft 31 May 2016

This version:
https://svgwg.org/svg2-draft/
Latest version:
http://www.w3.org/TR/SVG2/
Previous version:
http://www.w3.org/TR/2015/WD-SVG2-20150915/
Single page version:
https://svgwg.org/svg2-draft/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 http://www.w3.org/TR/.

This document is the 31 May 2016 Editor’s Draft 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 Editor’s Draft 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:

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, http://www.w3.org/Graphics/SVG/, that contains further background information. The authors of this document are the SVG Working Group participants.

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.

Publication as a Working Draft 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 http://www.w3.org/TR/. W3C publications may be updated, replaced, or obsoleted by other documents at any time.

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

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, Daniel Holbert, Paul LeBeau, Robert Longson, Henri Manson, Ms2ger, 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.

SVG 2 – 31 May 2016 TopContentsNextElementsAttributesProperties

SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

Full Table of Contents

  1. 1. Introduction
    1. 1.1. About SVG
    2. 1.2. Compatibility with other standards efforts
    3. 1.3. Conformance
  2. 2. Rendering Model
    1. 2.1. Introduction
    2. 2.2. The rendering tree
      1. 2.2.1. Definitions
      2. 2.2.2. Rendered versus non-rendered elements
      3. 2.2.3. Controlling visibility: the effect of the ‘display’ and ‘visibility’ properties
      4. 2.2.4. Re-used graphics
    3. 2.3. The painters model
    4. 2.4. Rendering order
      1. 2.4.1. Controlling element rendering order: the ‘z-index’ property
      2. 2.4.2. Establishing a stacking context in SVG
    5. 2.5. How elements are rendered
    6. 2.6. How groups are rendered
      1. 2.6.1. Object and group opacity: the effect of the ‘opacity’ property
    7. 2.7. Types of graphics elements
      1. 2.7.1. Painting shapes and text
      2. 2.7.2. Painting raster images
    8. 2.8. Filtering painted regions
    9. 2.9. Clipping and masking
    10. 2.10. Parent compositing
    11. 2.11. The effect of the ‘overflow’ property
  3. 3. Basic Data Types and Interfaces
    1. 3.1. Definitions
    2. 3.2. Attribute syntax
    3. 3.3. Real number precision
    4. 3.4. DOM interfaces for SVG elements
      1. 3.4.1. Interface SVGElement
      2. 3.4.2. Interface SVGGraphicsElement
      3. 3.4.3. Interface SVGGeometryElement
    5. 3.5. DOM interfaces for basic data types
      1. 3.5.1. Interface SVGNumber
      2. 3.5.2. Interface SVGLength
      3. 3.5.3. Interface SVGAngle
      4. 3.5.4. List interfaces
      5. 3.5.5. Interface SVGNumberList
      6. 3.5.6. Interface SVGLengthList
    6. 3.6. DOM interfaces for reflecting SVG attributes
      1. 3.6.1. Interface SVGAnimatedBoolean
      2. 3.6.2. Interface SVGAnimatedEnumeration
      3. 3.6.3. Interface SVGAnimatedInteger
      4. 3.6.4. Interface SVGAnimatedNumber
      5. 3.6.5. Interface SVGAnimatedLength
      6. 3.6.6. Interface SVGAnimatedAngle
      7. 3.6.7. Interface SVGAnimatedString
      8. 3.6.8. Interface SVGAnimatedRect
      9. 3.6.9. Interface SVGAnimatedNumberList
      10. 3.6.10. Interface SVGAnimatedLengthList
      11. 3.6.11. Interface SVGStringList
    7. 3.7. Other DOM interfaces
      1. 3.7.1. Interface SVGUnitTypes
      2. 3.7.2. Interface SVGTests
      3. 3.7.3. Interface SVGFitToViewBox
      4. 3.7.4. Interface SVGZoomAndPan
      5. 3.7.5. Interface SVGURIReference
  4. 4. Document Structure
    1. 4.1. Defining an SVG document fragment: the ‘svg’ element
      1. 4.1.1. Overview
      2. 4.1.2. Namespace
      3. 4.1.3. Definitions
      4. 4.1.4. The ‘svg’ element
    2. 4.2. Grouping: the ‘g’ element
      1. 4.2.1. Overview
      2. 4.2.2. The ‘g’ element
    3. 4.3. Unknown elements
    4. 4.4. Defining content for reuse, and the ‘defs’ element
      1. 4.4.1. Overview
      2. 4.4.2. The ‘defs’ element
    5. 4.5. The ‘desc’ and ‘title’ elements
      1. 4.5.1. Definition
    6. 4.6. The ‘metadata’ element
    7. 4.7. The ‘symbol’ element
      1. 4.7.1. Attributes
      2. 4.7.2. Notes on symbols
    8. 4.8. The ‘use’ element
      1. 4.8.1. Attributes
      2. 4.8.2. Re-usable graphics and the shadow tree
      3. 4.8.3. Layout
      4. 4.8.4. Style Inheritance
      5. 4.8.5. Event handling
    9. 4.9. Conditional processing
      1. 4.9.1. Conditional processing overview
      2. 4.9.2. Definitions
      3. 4.9.3. The ‘switch’ element
      4. 4.9.4. The ‘requiredExtensions’ attribute
      5. 4.9.5. The ‘systemLanguage’ attribute
    10. 4.10. HTML metadata elements
    11. 4.11. Common attributes
      1. 4.11.1. Definitions
      2. 4.11.2. Attributes common to all elements: ‘id’
      3. 4.11.3. The ‘lang’ and ‘xml:lang’ attributes
      4. 4.11.4. The ‘xml:space’ attribute
      5. 4.11.5. The ‘tabindex’ attribute
      6. 4.11.6. The ‘data-*’ attributes
    12. 4.12. WAI-ARIA attributes
      1. 4.12.1. Definitions
      2. 4.12.2. Role attribute
      3. 4.12.3. State and property attributes (all aria- attributes)
      4. 4.12.4. Implicit ARIA Semantics
    13. 4.13. DOM interfaces
      1. 4.13.1. Extensions to the Document interface
      2. 4.13.2. Interface SVGSVGElement
      3. 4.13.3. Interface SVGGElement
      4. 4.13.4. Interface SVGUnknownElement
      5. 4.13.5. Interface SVGDefsElement
      6. 4.13.6. Interface SVGDescElement
      7. 4.13.7. Interface SVGMetadataElement
      8. 4.13.8. Interface SVGTitleElement
      9. 4.13.9. Interface SVGSymbolElement
      10. 4.13.10. Interface SVGUseElement
      11. 4.13.11. Interface SVGSwitchElement
      12. 4.13.12. Interface GetSVGDocument
  5. 5. Styling
    1. 5.1. Styling SVG content using CSS
    2. 5.2. Inline style sheets: the ‘style’ element
    3. 5.3. External style sheets: the effect of the HTML ‘link’ element
    4. 5.4. Style sheets in HTML documents
    5. 5.5. Element-specific styling: the ‘class’ and ‘style’ attributes
    6. 5.6. Presentation attributes
    7. 5.7. Required properties
    8. 5.8. User agent style sheet
    9. 5.9. Required CSS features
    10. 5.10. DOM interfaces
      1. 5.10.1. Interface SVGStyleElement
  6. 6. Geometry Properties
    1. 6.1. Horizontal center coordinate: The ‘cx’ property
    2. 6.2. Vertical center coordinate: The ‘cy’ property
    3. 6.3. Radius: The ‘r’ property
    4. 6.4. Horizontal radius: The ‘rx’ property
    5. 6.5. Vertical radius: The ‘ry’ property
    6. 6.6. Horizontal coordinate: The ‘x’ property
    7. 6.7. Vertical coordinate: The ‘y’ property
    8. 6.8. Sizing properties: the effect of the ‘width’ and ‘height’ properties
  7. 7. Coordinate Systems, Transformations and Units
    1. 7.1. Introduction
    2. 7.2. Computing the equivalent transform of an SVG viewport
    3. 7.3. The initial viewport
    4. 7.4. The initial coordinate system
    5. 7.5. The ‘transform’ property
    6. 7.6. The ‘viewBox’ attribute
    7. 7.7. The ‘preserveAspectRatio’ attribute
    8. 7.8. Establishing a new SVG viewport
    9. 7.9. Units
    10. 7.10. Bounding boxes
    11. 7.11. Object bounding box units
    12. 7.12. Intrinsic sizing properties of the SVG viewport of SVG content
    13. 7.13. Vector effects
      1. 7.13.1. Computing the vector effects
      2. 7.13.2. Computing the vector effects for nested viewport coordinate systems
      3. 7.13.3. Examples of vector effects
    14. 7.14. DOM interfaces
      1. 7.14.1. Interface SVGTransform
      2. 7.14.2. Interface SVGTransformList
      3. 7.14.3. Interface SVGAnimatedTransformList
      4. 7.14.4. Interface SVGPreserveAspectRatio
      5. 7.14.5. Interface SVGAnimatedPreserveAspectRatio
  8. 8. Paths
    1. 8.1. Introduction
    2. 8.2. The ‘path’ element
    3. 8.3. Path data
      1. 8.3.1. General information about path data
      2. 8.3.2. Specifying path data: the ‘d’ property
      3. 8.3.3. The "moveto" commands
      4. 8.3.4. The "closepath" command
      5. 8.3.5. The "lineto" commands
      6. 8.3.6. The cubic Bézier curve commands
      7. 8.3.7. The quadratic Bézier curve commands
      8. 8.3.8. The elliptical arc curve commands
      9. 8.3.9. The bearing commands
      10. 8.3.10. The grammar for path data
    4. 8.4. Path directionality
    5. 8.5. Implementation notes
      1. 8.5.1. Error handling in path data
    6. 8.6. Distance along a path
      1. 8.6.1. The ‘pathLength’ attribute
    7. 8.7. DOM interfaces
      1. 8.7.1. Interface SVGPathElement
  9. 9. Basic Shapes
    1. 9.1. Introduction and definitions
    2. 9.2. The ‘rect’ element
    3. 9.3. The ‘circle’ element
    4. 9.4. The ‘ellipse’ element
    5. 9.5. The ‘line’ element
    6. 9.6. The ‘polyline’ element
    7. 9.7. The ‘polygon’ element
    8. 9.8. DOM interfaces
      1. 9.8.1. Interface SVGRectElement
      2. 9.8.2. Interface SVGCircleElement
      3. 9.8.3. Interface SVGEllipseElement
      4. 9.8.4. Interface SVGLineElement
      5. 9.8.5. Interface SVGAnimatedPoints
      6. 9.8.6. Interface SVGPointList
      7. 9.8.7. Interface SVGPolylineElement
      8. 9.8.8. Interface SVGPolygonElement
  10. 10. Text
    1. 10.1. Introduction
      1. 10.1.1. Definitions
      2. 10.1.2. Fonts and glyphs
      3. 10.1.3. Glyph metrics and layout
    2. 10.2. The ‘text’ and ‘tspan’ elements
      1. 10.2.1. Attributes
      2. 10.2.2. Notes on 'x', 'y', 'dx', 'dy' and 'rotate'
    3. 10.3. Text layout – Introduction
    4. 10.4. Text layout – Content Area
      1. 10.4.1. The ‘inline-size’ property
      2. 10.4.2. The ‘shape-inside’ property
      3. 10.4.3. The ‘shape-subtract’ property
      4. 10.4.4. The ‘shape-image-threshold’ property
      5. 10.4.5. The ‘shape-margin’ property
      6. 10.4.6. The ‘shape-padding’ property
    5. 10.5. Text layout – Algorithm
    6. 10.6. Pre-formatted text
      1. 10.6.1. Multi-line text via 'white-space'
      2. 10.6.2. Repositioning Glyphs
        1. 10.6.2.1. Text alignment, the ‘text-anchor’ property
    7. 10.7. Auto-wrapped text
      1. 10.7.1. Notes on Text Wrapping
        1. 10.7.1.1. First Line Positioning
        2. 10.7.1.2. Broken Lines
    8. 10.8. Text on a path
      1. 10.8.1. The ‘textPath’ element
      2. 10.8.2. Attributes
      3. 10.8.3. Text on a path layout rules
    9. 10.9. Text rendering order
    10. 10.10. Properties and pseudo-elements
      1. 10.10.1. SVG adaptions
        1. 10.10.1.1. The ‘font-variant’ property
        2. 10.10.1.2. The ‘kerning’ property
        3. 10.10.1.3. The ‘line-height’ property
        4. 10.10.1.4. The ‘writing-mode’ property
        5. 10.10.1.5. The ‘direction’ property
        6. 10.10.1.6. The ‘dominant-baseline’ property
        7. 10.10.1.7. The ‘alignment-baseline’ property
        8. 10.10.1.8. The ‘baseline-shift’ property
        9. 10.10.1.9. The ‘glyph-orientation-horizontal’ property
        10. 10.10.1.10. The ‘glyph-orientation-vertical’ property
        11. 10.10.1.11. The ‘text-overflow’ property
      2. 10.10.2. White space
        1. 10.10.2.1. SVG 2 Preferred white space handling, the ‘white-space’ property
        2. 10.10.2.2. Legacy white-space handling, the ‘xml:space’ property
        3. 10.10.2.3. Duplicate white-space directives
    11. 10.11. Text decoration
      1. 10.11.1. The ‘text-decoration-fill’ and ‘text-decoration-stroke’ properties
    12. 10.12. Text selection and clipboard operations
    13. 10.13. DOM interfaces
      1. 10.13.1. Interface SVGTextContentElement
      2. 10.13.2. Interface SVGTextPositioningElement
      3. 10.13.3. Interface SVGTextElement
      4. 10.13.4. Interface SVGTSpanElement
      5. 10.13.5. Interface SVGTextPathElement
  11. 11. Embedded Content
    1. 11.1. Overview
    2. 11.2. Placement of the referenced resource
    3. 11.3. The ‘image’ element
    4. 11.4. HTML5 elements in SVG subtrees
    5. 11.5. Foreign namespaces and private data
    6. 11.6. Embedding foreign object types
    7. 11.7. The ‘foreignObject’ element
    8. 11.8. DOM interfaces
      1. 11.8.1. Interface SVGImageElement
      2. 11.8.2. Interface SVGForeignObjectElement
  12. 12. Painting: Filling, Stroking and Marker Symbols
    1. 12.1. Introduction
      1. 12.1.1. Definitions
    2. 12.2. Specifying paint
    3. 12.3. The effect of the ‘color’ property
    4. 12.4. Fill properties
      1. 12.4.1. Specifying fill paint: the ‘fill’ property
      2. 12.4.2. Winding rule: the ‘fill-rule’ property
      3. 12.4.3. Fill paint opacity: the ‘fill-opacity’ property
    5. 12.5. Stroke properties
      1. 12.5.1. Specifying stroke paint: the ‘stroke’ property
      2. 12.5.2. Stroke paint opacity: the ‘stroke-opacity’ property
      3. 12.5.3. Stroke width: the ‘stroke-width’ property
      4. 12.5.4. Drawing caps at the ends of strokes: the ‘stroke-linecap’ property
      5. 12.5.5. Controlling line joins: the ‘stroke-linejoin’ and ‘stroke-miterlimit’ properties
      6. 12.5.6. Dashing strokes: the ‘stroke-dasharray’ and ‘stroke-dashoffset’ properties
      7. 12.5.7. Computing the shape of the stroke
      8. 12.5.8. Computing the circles for the arcs 'stroke-linejoin'
    6. 12.6. Vector effects
    7. 12.7. Markers
      1. 12.7.1. The ‘marker’ element
      2. 12.7.2. Vertex markers: the ‘marker-start’, ‘marker-mid’ and ‘marker-end’ properties
      3. 12.7.3. Marker shorthand: the ‘marker’ property
      4. 12.7.4. Rendering markers
    8. 12.8. Controlling paint operation order: the ‘paint-order’ property
    9. 12.9. Color space for interpolation: the ‘color-interpolation’ property
    10. 12.10. Rendering hints
      1. 12.10.1. The ‘color-rendering’ property
      2. 12.10.2. The ‘shape-rendering’ property
      3. 12.10.3. The ‘text-rendering’ property
      4. 12.10.4. The ‘image-rendering’ property
    11. 12.11. The effect of the ‘will-change’ property
    12. 12.12. DOM interfaces
      1. 12.12.1. Interface SVGMarkerElement
  13. 13. Paint Servers: Solid Colors, Gradients, Patterns and Hatches
    1. 13.1. Introduction
    2. 13.2. Solid colors
      1. 13.2.1. Properties
    3. 13.3. Gradients
      1. 13.3.1. Definitions
      2. 13.3.2. Linear gradients
        1. 13.3.2.1. Attributes
        2. 13.3.2.2. Notes on linear gradients
      3. 13.3.3. Radial gradients
        1. 13.3.3.1. Attributes
        2. 13.3.3.2. Notes on radial gradients
      4. 13.3.4. Mesh gradients
        1. 13.3.4.1. Mesh Structure
        2. 13.3.4.2. Painting a Mesh Patch
        3. 13.3.4.3. Attributes
      5. 13.3.5. Gradient stops
        1. 13.3.5.1. Attributes
        2. 13.3.5.2. Properties
        3. 13.3.5.3. Notes on gradient stops
    4. 13.4. Patterns
      1. 13.4.1. Attributes
      2. 13.4.2. Notes on patterns
    5. 13.5. Hatches
      1. 13.5.1. Attributes
      2. 13.5.2. Notes on hatches
      3. 13.5.3. Hatch paths
        1. 13.5.3.1. Attributes
        2. 13.5.3.2. Notes on hatch paths
    6. 13.6. DOM interfaces
      1. 13.6.1. Interface SVGSolidcolorElement
      2. 13.6.2. Interface SVGGradientElement
      3. 13.6.3. Interface SVGLinearGradientElement
      4. 13.6.4. Interface SVGRadialGradientElement
      5. 13.6.5. Interface SVGMeshElement
      6. 13.6.6. Interface SVGMeshrowElement
      7. 13.6.7. Interface SVGMeshpatchElement
      8. 13.6.8. Interface SVGStopElement
      9. 13.6.9. Interface SVGPatternElement
      10. 13.6.10. Interface SVGHatchElement
      11. 13.6.11. Interface SVGHatchpathElement
  14. 14. Scripting and Interactivity
    1. 14.1. Introduction
    2. 14.2. Supported events
    3. 14.3. User interface events
    4. 14.4. Pointer events
    5. 14.5. Hit-testing and processing order for user interface events
      1. 14.5.1. Hit-testing
      2. 14.5.2. Event processing
    6. 14.6. The ‘pointer-events’ property
    7. 14.7. Magnification and panning
    8. 14.8. Cursors
      1. 14.8.1. The effect of the ‘cursor’ property
      2. 14.8.2. The ‘cursor’ element
    9. 14.9. Focus
    10. 14.10. Event attributes
      1. 14.10.1. Animation event attributes
    11. 14.11. The ‘script’ element
    12. 14.12. DOM interfaces
      1. 14.12.1. Interface SVGCursorElement
      2. 14.12.2. Interface SVGScriptElement
  15. 15. Linking
    1. 15.1. References
      1. 15.1.1. Overview
      2. 15.1.2. Definitions
      3. 15.1.3. URLs and URIs
      4. 15.1.4. Syntactic forms: URL and <url>
      5. 15.1.5. Processing of URL references
      6. 15.1.6. URL reference attributes
      7. 15.1.7. Deprecated XLink URL reference attributes
    2. 15.2. Links out of SVG content: the ‘a’ element
    3. 15.3. Linking into SVG content: URL fragments and SVG views
      1. 15.3.1. SVG fragment identifiers
      2. 15.3.2. SVG fragment identifiers definitions
      3. 15.3.3. Predefined views: the ‘view’ element
    4. 15.4. DOM interfaces
      1. 15.4.1. Interface SVGAElement
      2. 15.4.2. Interface SVGViewElement
  16. Appendix A: SVG Document Object Model (DOM)
    1. A.1. SVG DOM overview
      1. A.1.1. SVG DOM object initialization
    2. A.2. Elements in the SVG DOM
    3. A.3. Naming conventions
    4. A.4. Relationship with DOM Level 3 Events
    5. A.5. Relationship with DOM Level 2 CSS
      1. A.5.1. User agents that support styling with CSS
    6. A.6. Invalid values
  17. Appendix B: IDL Definitions
  18. Appendix C: Implementation Requirements
    1. C.1. Introduction
    2. C.2. Error processing
    3. C.3. Clamping values which are restricted to a particular range
    4. C.4. Elliptical arc implementation notes
      1. C.4.1. Elliptical arc syntax
      2. C.4.2. Out-of-range parameters
      3. C.4.3. Parameterization alternatives
      4. C.4.4. Conversion from center to endpoint parameterization
      5. C.4.5. Conversion from endpoint to center parameterization
      6. C.4.6. Correction of out-of-range radii
    5. C.5. Text selection implementation notes
    6. C.6. Printing implementation notes
  19. Appendix D: Conformance Criteria
    1. D.1. Introduction
    2. D.2. Conforming SVG Document Fragments
    3. D.3. Conforming SVG Stand-Alone Files
    4. D.4. Conforming SVG Generators
    5. D.5. Conforming SVG Servers
    6. D.6. Conforming SVG DOM Subtree
    7. D.7. Conforming SVG Interpreters
    8. D.8. Conforming SVG Viewers
  20. Appendix E: Accessibility Support
    1. E.1. SVG Accessibility Features
    2. E.2. Supporting SVG Accessibility Specifications and Guidelines
  21. Appendix F: References
    1. F.1. Normative references
    2. F.2. Informative references
  22. Appendix G: Element Index
  23. Appendix H: Attribute Index
    1. H.1. Regular attributes
    2. H.2. Presentation attributes
  24. Appendix I: Property Index
  25. Appendix J: IDL Index
  26. Appendix K: Media Type Registration for image/svg+xml
    1. K.1. Introduction
    2. K.2. Registration of media type image/svg+xml
  27. Appendix L: Changes from SVG 1.1
    1. L.1. Editorial changes
    2. L.2. Substantial changes
      1. L.2.1. Across the whole document
      2. L.2.2. Concepts
      3. L.2.3. Rendering Model chapter
      4. L.2.4. Basic Data Types and Interfaces chapter
      5. L.2.5. Document Structure chapter
      6. L.2.6. Styling chapter
      7. L.2.7. Geometry Properties chapter
      8. L.2.8. Coordinate Systems, Transformations and Units chapter
      9. L.2.9. Paths chapter
      10. L.2.10. Basic Shapes chapter
      11. L.2.11. Text chapter
      12. L.2.12. Embedded Content chapter
      13. L.2.13. Painting chapter
      14. L.2.14. Color chapter
      15. L.2.15. Paint Servers chapter
      16. L.2.16. Clipping, Masking and Compositing chapter
      17. L.2.17. Filter Effects chapter
      18. L.2.18. Interactivity chapter
      19. L.2.19. Linking chapter
      20. L.2.20. Scripting chapter
      21. L.2.21. Animation chapter
      22. L.2.22. Fonts chapter
      23. L.2.23. Extensibility chapter
      24. L.2.24. Document Type Definition appendix
      25. L.2.25. SVG Document Object Model (DOM) appendix
      26. L.2.26. Java Language Binding appendix
      27. L.2.27. ECMAScript Language Binding appendix
      28. L.2.28. References appendix
      29. L.2.29. IDL Index appendix
      30. L.2.30. Feature Strings
SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

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 [XML10]. 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. Conformance

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.

SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

Chapter 2: 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.

2.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).

2.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.

2.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. Does not include elements that are only in the rendering tree as re-used graphics. 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. Includes markers, paint server content, and content duplicated by use elements, as well as graphics used in clipPath or mask.

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, linearGradient, marker, mask, metadata, pattern, radialGradient, script, symbol and title

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, use and video

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

2.2.2. Rendered versus non-rendered elements

At any given time, an SVG element 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.

2.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. [CSS21]

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 text content 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 and text content elements. Since visibility is an inherited property, however, although it has no effect on a container element itself, its inherited value can affect descendant elements.

2.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. This includes the graphics created by style properties (such as a pattern paint server, or line markers) as well as graphics that are instantiated with a use element. In the case of use instances, the original graphical elements may or may not be rendered themselves.

Each instance of the re-used graphics creates a fragment of the rendering tree. The component graphics may need their styles resolved based on context, then they are rendered and composited as described in this chapter. The re-used fragment as a whole is treated as a stacking context and a non-isolated group.

The display property on any child content of re-used graphics has its normal effect when set to none, preventing that branch of the document fragment from being used in rendering. Similarly, when a use element references a renderable element (as opposed to a symbol), a value of display: none on the referenced element will result in an empty rendering-tree fragment for that 'use' element. However, re-used graphics are never affected when the original DOM elements themselves are not rendered because of a value of display: none on an ancestor.

2.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.

2.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.

2.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. [CSS21]

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.

2.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.

2.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.

2.6. How groups are rendered

Grouping elements, such as the g element (see container elements ) create a compositing group. 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.

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

See the CSS Color Module Level 3 for the definition of opacity. [CSS3COLOR]

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, graphics elements and text content child 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:

2.7. Types of graphics elements

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

2.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.

2.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.

2.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.

2.9. Clipping and masking

SVG supports the following clipping/masking features:

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

2.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 the SVG document is a top-level document, the top level SVG element is considered to be the page group and is composited with a backdrop of white with 100% opacity. For all other referencing modes, there is no page group. The SVG document is composited into the parent document with opacity preserved.

2.11. The effect of the ‘overflow’ property

See the Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification [CSS21] 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
textvisiblehiddenvisiblevisiblehiddenhidden
patternvisiblehiddenvisiblevisiblehiddenhidden
hatchesvisiblehiddenvisiblevisiblehiddenhidden
markervisiblehiddenvisiblevisiblehiddenhidden
symbolvisiblehiddenvisiblevisiblehiddenhidden
imagevisiblehiddenvisiblevisiblehiddenhidden
iframevisiblen/avisiblevisiblehiddenhidden
foreignObjectvisiblen/avisiblevisiblehiddenhidden

The overflow property has the same parameter values and has the same meaning as defined in CSS 2.1 ([CSS21], 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.
SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

Chapter 3: Basic Data Types and Interfaces

3.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 ([CSS21], section 4.1.8).

3.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 [CSS3VALUES]. 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 [XML10]. For external definitions, this is indicated by [EBNF] appearing in the Value column.
  3. By reference to an ABNF symbol defined in another specification [STD68]. 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.

3.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.

3.4. DOM interfaces for SVG elements

3.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;

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.

3.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.

3.4.3. Interface SVGGeometryElement

Interface SVGGeometryElement represents SVG elements whose rendering is defined by geometry and which can be filled and stroked. This includes paths, text 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).

3.5. DOM interfaces for basic data types

3.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.

3.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.

3.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.

3.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.

3.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.

3.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.

3.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.

3.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.

3.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.

3.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.

3.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.

3.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:

3.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:

3.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.

3.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.

3.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.

3.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.

3.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.

3.7. Other DOM interfaces

3.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.

3.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.

3.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.

3.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.

3.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.

SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

Chapter 4: Document Structure

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

4.1.1. Overview

The content model and set of allowed attributes, as listed in definitions.xml, needs to be reviewed for consistency across all elements.

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.)

4.1.2. Namespace

When SVG is parsed as a XML, for compliance with the Namespaces in XML Recommendation [XML-NS], 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-NS].

4.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.
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.

A "user agent" may or may not have the ability to retrieve and render SVG content; however, an "SVG user agent" retrieves and renders SVG content.

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. When an svg element is a descendant of another svg element, only the outermost svg element is 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, path, polygon, polyline, rect, text, use 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, use and video.

4.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, clipPath, cursor, filter, foreignObject, image, marker, mask, script, style, switch, text, 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.

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.

4.2. Grouping: the ‘g’ element

4.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 and symbol.

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.

4.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, clipPath, cursor, filter, foreignObject, image, marker, mask, script, style, switch, text, view
Attributes:
DOM Interfaces:

4.3. Unknown elements

SVG 2 Requirement: Have unknown elements treated as g for the purpose of rendering.
Resolution: Accept having unknown elements treated as ‘g’ for the purpose of rendering.
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:
None
Content model:
Any elements or character data.
Attributes:
DOM Interfaces:

The SVGUnknownElement interface must be used for elements in the SVG namespace that are not defined by 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.

Unknown elements in the SVG namespace render as if the unknown element was a g element.

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.

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)

Do we need to mention anything about attributes, properties and such on SVGUnknownElements?

Should SVGUnknownElement be a container element?

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

4.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, wherever possible, referenced elements be defined inside of a defs element. Among the elements that are always referenced: clipPath, cursor, filter, linearGradient, marker, mask, pattern, radialGradient and symbol.

4.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, clipPath, cursor, filter, foreignObject, image, marker, mask, script, style, switch, text, 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; they are prevented from becoming part of the rendering tree just as if the defs element were a g element and the display property were set to none. 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 or any of its descendants does not prevent those elements from being referenced by other elements.

4.5. The ‘desc’ and ‘title’ elements

4.5.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.
desc
Categories:
Descriptive element, never-rendered element
Content model:
Any elements or character data.
Attributes:
DOM Interfaces:
title
Categories:
Descriptive element, never-rendered element
Content model:
Any elements or character data.
Attributes:
DOM Interfaces:

The attribute lang 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.

Multiple sibling desc or title elements must have different lang attributes. The element whose lang attribute best matches the language set by the user agent will be used as the title or desc. If no match exists, the first element must be used. If multiple equally valid matches exist, the first match is used.

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

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 the image credit or short description of the object; on interactive content, it could be a label for, or instructions for, use of the element; and so forth.

Interactive User agents commonly render title elements as a tooltip on hovering the parent element.

User agents should make title and desc elements available to platform accessibility APIs as per SVG-AAM.

Authors should not provide both a visible label for a drawing element by using a text element, and a title element, as they will be both presented, redundantly, to users.

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 help information about the element.

Authors should provide a title child element to the outermost 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 outermost svg element available to users.

Unlike the desc element, authors also have the ability to associate more detailed information with content that includes visible text. This can be achieved by applying aria-describedby to the element, or container of elements being described and passing an ID reference to content that includes text that describes the element in question. However, if the text describing the object is hidden the text within the description would be exposed to assistive technologies as detailed text information, similar to a descendant desc element. The aria-describedby attribute takes precedence over the child desc when providing a description, consequently authors should only use aria-describedby when an element is described by visible text on the screen, otherwise the use of a child desc is preferred.

Alternate presentations are possible, both visual and aural, which display the desc and title elements but do not display path elements or other graphics elements. For deep hierarchies, and for following use element references, it is sometimes desirable to allow the user to control how deep they drill down into descriptive text.

The following is an example. In typical operation, the SVG user agent would not render the desc and title elements but would render the remaining contents of the g element.

<?xml version="1.0" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg"
     viewBox="0 0 400 300">
  <g>
    <title>Company sales by region</title>
    <title lang="fr">Chiffre d'affaires par région</title>
    <desc>Bar chart which shows company sales by region.</desc>
    <desc lang="fr">Graphique illustrant les ventes par région.</desc>
    <line x1="30" y1="10" x2="380" y2="270"/>
  </g>
</svg>

Description and title elements can contain marked-up text from other namespaces.

We should say what purpose including other-namespaced markup in title and desc has. If it is just that these are basically metadata extension points for other profiles or uses of SVG, then we should say that.

4.6. 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-NS].

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:

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>

4.7. The ‘symbol’ element

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

4.7.1. Attributes

Name Value Initial value Animatable
refX <length> | left | center | right 0 yes
refY <length> | top | center | bottom 0 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 position as defined by the use element. They are interpreted as being in the coordinate system of the symbol contents, after application of the viewBox and preserveAspectRatio attributes.

4.7.2. Notes on symbols

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

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.

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 display property does not apply to the symbol element; thus, symbol elements are not directly rendered even if the display property is set to a value other than none, and symbol elements are available for referencing even when the display property on the symbol element or any of its ancestors is set to none.

4.8. 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 element, graphics referencing element, renderable element, structural element, structurally external element
Content model:
Any number of the following elements, in any order:clipPath, marker, mask, script
Attributes:
DOM Interfaces:

The use element references another element and indicates that a copy of the graphical contents of that element is rendered at that given point in the document. These re-used graphics inherit styles from the use element and in certain cases can be re-sized. However, they remain linked to the referenced source and reflect DOM mutations, animations, and style changes in the original.

4.8.1. Attributes

Name Value Initial value Animatable
x, y <length> 0 yes
width, height <length> (see below) yes

The x, y, width and height attributes specify the positioning of the referenced element. The width and height attributes have different initial values depending on the type of the referenced element:

svg
The initial values are the width and height presentation attribute values from the referenced svg element.
anything else
The initial values are '100%'.

A negative value for width or height is an error (see Error processing). If width or height is zero then rendering of the use element is disabled.

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.

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

4.8.2. Re-usable graphics and the shadow tree

The graphical contents are any svg, symbol, g, graphics element or other use elements, that a use element references.

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.

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

The effect of a use element is as if the contents of the referenced element were deeply cloned into a separate non-exposed DOM tree which had the use element as its parent and all of the use element's ancestors as its higher-level ancestors. Because the cloned DOM tree is non-exposed, the SVG Document Object Model (DOM) only contains the use element and its attributes. The SVG DOM does not show the referenced element's contents as children of use element.

The non-exposed DOM tree must be created even if 'display: none' is set on the use element. Note that script elements that get conceptually cloned into the non-exposed DOM tree do not execute again, and audio and video elements that may play audio must only do so if the use element is rendered.

A use element has the same visual effect as if the use element were replaced by the following generated content:

Except that the replaced content shouldn't affect how styles are matched.

In the generated content, the use will be replaced by g, where all attributes from the use element except for x, y, width, height, href and xlink:href are transferred to the generated g element. An additional transformation translate(x,y) is appended to the end (i.e., right-side) of the transform property on the generated g, where x and y represent the values of the x and y attributes on the use element.

The element referenced by use may be in a separate document. However, this specification does not define how or if the user agent will process stylesheets in that document, or what SVG viewport will be used for resolving percentages and media queries in such documents, if animations run in the separate document and which document controls the animation timeline. Script elements in the resource document must not be executed, and the corresponding conceptually cloned script elements must also not execute.

When re-using external assets, therefore, authors are advised not to include any scripts in the external file and to use inline styles or presentation attributes only. Percentage lengths should only be used if the re-used assets define their own SVG viewport (i.e., if the re-used element is an svg or symbol). Declarative animations in external assets should not be used.

User agents may restrict 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 a use references another element which is another use or whose content contains a use element, then the deep 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 error, as described in References and the ‘defs’ element.

4.8.3. Layout

The use element has optional attributes x, y, width and height which are used to map the graphical contents of the referenced element onto a rectangular region within the current coordinate system.

4.8.4. Style Inheritance

The conceptual deep cloning of the referenced element into a non-exposed DOM tree also copies any property values resulting from the CSS cascade ([CSS21], chapter 6) on the referenced element and its contents. CSS2 selectors can be applied to the original (i.e., referenced) elements because they are part of the formal document structure. CSS2 selectors cannot be applied to the (conceptually) cloned DOM tree because its contents are not part of the formal document structure.

Property inheritance, however, works as if the referenced element had been textually included as a deeply cloned child of the use element. The referenced element inherits properties from the use element and the use element's ancestors. An instance of a referenced element does not inherit properties from the referenced element's original parents.

Note that specifying 'visibility:hidden' on a use element does not guarantee that the referenced content will not be rendered. If the use element specifies 'visibility:hidden' and the element it references specifies 'visibility:hidden' or 'visibility:inherit', then that one element will be hidden. However, if the referenced element instead specifies 'visibility:visible', then that element will be visible even if the use element specifies 'visibility:hidden'.

Animations on a referenced element will cause the instances to also be animated.

For user agents that support Styling with CSS, the generated g element carries along with it the "cascaded" property values on the use element which result from the CSS cascade ([CSS21], chapter 6). Additionally, the copy (deep clone) of the referenced resource carries along with it the "cascaded" property values resulting from the CSS cascade on the original (i.e., referenced) elements. Thus, the result of various CSS selectors in combination with the class and style attributes are, in effect, replaced by the functional equivalent of a style attribute in the generated content which conveys the "cascaded" property values.

Example Use01 below has a simple use on a rect.

<?xml version="1.0" standalone="no"?>
<svg width="10cm" height="3cm" viewBox="0 0 100 30" version="1.1"
     xmlns="http://www.w3.org/2000/svg">
  <desc>Example Use01 - Simple case of 'use' on a 'rect'</desc>
  <defs>
    <rect id="MyRect" width="60" height="10"/>
  </defs>
  <rect x=".1" y=".1" width="99.8" height="29.8"
        fill="none" stroke="blue" stroke-width=".2" />
  <use x="20" y="10" href="#MyRect" />
</svg>
Example Use01 — Simple case of 'use' on a 'rect'

Example Use01

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

The visual effect would be equivalent to the following document:

<?xml version="1.0" standalone="no"?>
<svg width="10cm" height="3cm" viewBox="0 0 100 30"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
  <desc>Example Use01-GeneratedContent - Simple case of 'use' on a 'rect'</desc>
  <!-- 'defs' section left out -->

  <rect x=".1" y=".1" width="99.8" height="29.8"
        fill="none" stroke="blue" stroke-width=".2" />

  <!-- Start of generated content. Replaces 'use' -->
  <g transform="translate(20,10)">
    <rect width="60" height="10"/>
  </g>
  <!-- End of generated content -->

</svg>

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

Example Use02 below has a use on a symbol.

<?xml version="1.0" standalone="no"?>
<svg width="10cm" height="3cm" viewBox="0 0 100 30" version="1.1"
     xmlns="http://www.w3.org/2000/svg">
  <desc>Example Use02 - 'use' on a 'symbol'</desc>
  <defs>
    <symbol id="MySymbol" viewBox="0 0 20 20">
      <desc>MySymbol - four rectangles in a grid</desc>
      <rect x="1" y="1" width="8" height="8"/>
      <rect x="11" y="1" width="8" height="8"/>
      <rect x="1" y="11" width="8" height="8"/>
      <rect x="11" y="11" width="8" height="8"/>
    </symbol>
  </defs>
  <rect x=".1" y=".1" width="99.8" height="29.8"
        fill="none" stroke="blue" stroke-width=".2" />
  <use x="45" y="10" width="10" height="10" href="#MySymbol" />
</svg>
Example Use02 — 'use' on a 'symbol'

Example Use02

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

The visual effect would be equivalent to the following document:

<?xml version="1.0" standalone="no"?>
<svg width="10cm" height="3cm" viewBox="0 0 100 30"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
  <desc>Example Use02-GeneratedContent - 'use' on a 'symbol'</desc>

  <!-- 'defs' section left out -->

  <rect x=".1" y=".1" width="99.8" height="29.8"
        fill="none" stroke="blue" stroke-width=".2" />

  <!-- Start of generated content. Replaces 'use' -->
  <g transform="translate(45, 10)" >
    <!-- Start of referenced 'symbol'. 'symbol' replaced by 'svg',
         with x,y,width,height=0,0,100%,100% -->
    <svg width="10" height="10" 
         viewBox="0 0 20 20">
      <rect x="1" y="1" width="8" height="8"/>
      <rect x="11" y="1" width="8" height="8"/>
      <rect x="1" y="11" width="8" height="8"/>
      <rect x="11" y="11" width="8" height="8"/>
    </svg>
    <!-- End of referenced symbol -->
  </g>
  <!-- End of generated content -->

</svg>

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

Example Use03 illustrates what happens when a use has a transform property.

<?xml version="1.0" standalone="no"?>
<svg width="10cm" height="3cm" viewBox="0 0 100 30" version="1.1"
     xmlns="http://www.w3.org/2000/svg">
  <desc>Example Use03 - 'use' with a 'transform' attribute</desc>
  <defs>
    <rect id="MyRect" x="0" y="0" width="60" height="10"/>
  </defs>
  <rect x=".1" y=".1" width="99.8" height="29.8"
        fill="none" stroke="blue" stroke-width=".2" />
  <use href="#MyRect"
       transform="translate(20,2.5) rotate(10)" />
</svg>
Example Use03 — 'use' with a 'transform' property

Example Use03

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

The visual effect would be equivalent to the following document:

<?xml version="1.0" standalone="no"?>
<svg width="10cm" height="3cm" viewBox="0 0 100 30"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
  <desc>Example Use03-GeneratedContent - 'use' with a 'transform' attribute</desc>

  <!-- 'defs' section left out -->

  <rect x=".1" y=".1" width="99.8" height="29.8"
        fill="none" stroke="blue" stroke-width=".2" />

  <!-- Start of generated content. Replaces 'use' -->
  <g transform="translate(20,2.5) rotate(10)">
    <rect x="0" y="0" width="60" height="10"/>
  </g>
  <!-- End of generated content -->

</svg>

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

Example Use04 illustrates a use element with various methods of applying CSS styling.

<?xml version="1.0" standalone="no"?>
<svg width="12cm" height="3cm" viewBox="0 0 1200 300"
     xmlns="http://www.w3.org/2000/svg">
  <desc>Example Use04 - 'use' with CSS styling</desc>
  <defs style=" /* rule 9 */ stroke-miterlimit: 10" >
    <path id="MyPath" d="M300 50 L900 50 L900 250 L300 250"
                     class="MyPathClass"
                     style=" /* rule 10 */ stroke-dasharray:300,100" />
  </defs>
  <style type="text/css">
    <![CDATA[
      /* rule 1 */ #MyUse { fill: blue }
      /* rule 2 */ #MyPath { stroke: red }
      /* rule 3 */ use { fill-opacity: .5 }
      /* rule 4 */ path { stroke-opacity: .5 }
      /* rule 5 */ .MyUseClass { stroke-linecap: round }
      /* rule 6 */ .MyPathClass { stroke-linejoin: bevel }
      /* rule 7 */ use > path { shape-rendering: optimizeQuality }
      /* rule 8 */ g > path { visibility: hidden }
    ]]>
  </style>

  <rect x="0" y="0" width="1200" height="300"
         style="fill:none; stroke:blue; stroke-width:3"/>
  <g style=" /* rule 11 */ stroke-width:40">
    <use id="MyUse" href="#MyPath"
         class="MyUseClass"
         style="/* rule 12 */ stroke-dashoffset:50" />
  </g>
</svg>
Example Use04 — 'use' with CSS styling

Example Use04

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

The visual effect would be equivalent to the following document. Observe that some of the style rules above apply to the generated content (i.e., rules 1-6, 10-12), whereas others do not (i.e., rules 7-9). The rules which do not affect the generated content are:

In the generated content below, the selectors that yield a match have been transferred into inline style attributes for illustrative purposes.

<?xml version="1.0" standalone="no"?>
<svg width="12cm" height="3cm" viewBox="0 0 1200 300"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
  <desc>Example Use04-GeneratedContent - 'use' with a 'transform' attribute</desc>

  <!-- 'style' and 'defs' sections left out -->

  <rect x="0" y="0" width="1200" height="300"
         style="fill:none; stroke:blue; stroke-width:3"/>
  <g style="/* rule 11 */ stroke-width:40">

    <!-- Start of generated content. Replaces 'use' -->
    <g style="/* rule 1 */ fill:blue;
                 /* rule 3 */ fill-opacity:.5;
                 /* rule 5 */ stroke-linecap:round;
                 /* rule 12 */ stroke-dashoffset:50" >
      <path d="M300 50 L900 50 L900 250 L300 250"
            style="/* rule 2 */ stroke:red; 
                   /* rule 4 */ stroke-opacity:.5; 
                   /* rule 6 */ stroke-linejoin: bevel; 
                   /* rule 10 */ stroke-dasharray:300,100" />
    </g> 
    <!-- End of generated content -->

  </g>
</svg>

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

4.8.5. Event handling

If event attributes are assigned to referenced elements, then the actual target for the event will be the element within the "instance tree" corresponding to the given referenced element.

The event handling for the non-exposed tree works as if the referenced element had been textually included as a deeply cloned child of the use element, and events are dispatched according to the shadow tree event dispatching algorithm [SHADOWDOM]. The event's target and currentTarget attributes are set to the instance tree element that corresponds to the target and current target elements in the referenced subtree. An event propagates through the exposed and non-exposed portions of the tree in the same manner as it would in the regular document tree: first going from the root element to the use element and then through non-exposed tree elements in the capture phase, followed by the target phase at the target of the event, then bubbling back through non-exposed tree to the use element and then back through regular tree to the root element in bubbling phase. In order to maintain encapsulation events must use the event retargeting algorithm [SHADOWDOM] when crossing from a non-exposed tree to the regular tree.

We should define the behavior of use in terms of Web Components. See ACTION-3729 (Tab) Github Issue #99

4.9. Conditional processing

4.9.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.

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:

4.9.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 1.1 are requiredExtensions and systemLanguage.

4.9.3. The ‘switch’ element

switch
Categories:
Container element, renderable element
Content model:
Any number of the following elements, in any order:a, clipPath, foreignObject, g, image, marker, mask, script, svg, switch, text, use
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.

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.

4.9.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.

4.9.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.

4.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.

4.11. Common attributes

4.11.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.

4.11.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 [DOM4]. The id attribute must be any value other than the empty string.

4.11.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 [XML10].

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].

4.11.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 [XML10] and to the discussion white space handling in SVG.

New content should use the white-space property instead.

4.11.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.

4.11.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.

4.12. WAI-ARIA attributes

4.12.1. Definitions

ARIA attributes
These are the attributes used consisting of WAI-ARIA states and properties as well as the role attribute whose values are defined defined in WAI-ARIA. 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-label, aria-labelledby, aria-level, aria-atomic, 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-live.

Note that the above list ARIA attributes is likely to change in an upcoming version of the SVG Accessibility API mappings specification..

4.12.2. Role attribute

SVG elements having native semantics that are not limited to presentation (having "no role"), may have an ARIA role attribute specified. 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 ([ARIA], section 5.4) and Graphics Roles ([ARIA-GRAPHICS], section 4).

The WAI-ARIA role that an SVG element has assigned to it is the first non-abstract role found in the list of values generated when the role attribute is split on spaces.

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 ([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.

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

SVG elements having native semantics that are not limited to presentation (having "no role"), may have an may have WAI-ARIA state and property attributes specified. These attributes are defined by ARIA in Definitions of States and Properties (all aria-* attributes) ([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 ([ARIA], section 10.2).

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. [ARIA] [SVG-AAM]

4.12.4. Implicit 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.

Language featureDefault implied ARIA semanticsRestrictions
a link role no restrictions
audio group role If specified, role must be application
canvas group role no restrictions
circle none role provided no associated title element, desc element, aria-label attribute, aria-labelledby attribute, aria-describedby attribute; or tabindex attribute; otherwise, group role no restrictions
clipPath none no role may be applied
cursor none no restrictions
defs none no role may be applied
desc none no role may be applied
ellipse none role provided no associated title element, desc element, aria-label attribute, aria-labelledby attribute, aria-describedby attribute; or tabindex attribute; otherwise, group role 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 none role provided no associated title element, desc element, aria-label attribute, aria-labelledby attribute, aria-describedby attribute; or tabindex attribute; otherwise, group role no restrictions
g none role provided no associated title element, desc element, aria-label attribute, aria-labelledby attribute, aria-describedby attribute; or tabindex attribute; otherwise, group role no restrictions
hatch none no role may be applied
hatchpath none no role may be applied
iframe no role If Specified, role must be either application, document, or img roles
image img role no restrictions
line none role provided no associated title element, desc element, aria-label attribute, aria-labelledby attribute, aria-describedby attribute; or tabindex attribute; otherwise, group role no restrictions
linearGradient none no role may be applied
marker none no role may be applied
mask none no role may be applied
mesh none role provided no associated title element, desc element, aria-label attribute, aria-labelledby attribute, aria-describedby attribute; or tabindex attribute; otherwise, img role no restrictions
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 none role provided no associated title element, desc element, aria-label attribute, aria-labelledby attribute, aria-describedby attribute; or tabindex attribute; otherwise, group role no restrictions
pattern none no role may be applied
polygon none role provided no associated title element, desc element, aria-label attribute, aria-labelledby attribute, aria-describedby attribute; or tabindex attribute; otherwise, group role no restrictions
polyline none role provided no associated title element, desc element, aria-label attribute, aria-labelledby attribute, aria-describedby attribute; or tabindex attribute; otherwise, group role no restrictions
radialGradient none no role may be applied
rect none role provided no associated title element, desc element, aria-label attribute, aria-labelledby attribute, aria-describedby attribute; or tabindex attribute; otherwise, group role 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-doc role no restrictions
switch none role provided no associated title element, desc element, aria-label attribute, aria-labelledby attribute, aria-describedby attribute; or tabindex attribute; otherwise, group role no restrictions
symbol none role provided no associated title element, desc element, aria-label attribute, aria-labelledby attribute, aria-describedby attribute; or tabindex attribute; otherwise, group role no restrictions
text group role no restrictions
textPath group role no restrictions
title none no role may be applied
tspan none role provided no associated title element, desc element, aria-label attribute, aria-labelledby attribute, aria-describedby attribute; or tabindex attribute; otherwise, group role no restrictions
use none role provided no associated title element, desc element, aria-label attribute, aria-labelledby attribute, aria-describedby attribute; or tabindex attribute; otherwise, graphics-symbol role no restrictions
video group role If specified, role must be application
view none role provided no associated title element, desc element, aria-label attribute, aria-labelledby attribute, aria-describedby attribute; or tabindex attribute; otherwise, group role no restrictions

4.13. DOM interfaces

4.13.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.

4.13.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);

  // 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 child 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 specific content referenced by the use element, we don't place the referencing content 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. ([DOM4], 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. [DOM4][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.

4.13.3. Interface SVGGElement

An SVGGElement object represents a g element in the DOM.

interface SVGGElement : SVGGraphicsElement {
};

4.13.4. Interface SVGUnknownElement

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

interface SVGUnknownElement : SVGGraphicsElement {
};

4.13.5. Interface SVGDefsElement

An SVGDefsElement object represents a defs element in the DOM.

interface SVGDefsElement : SVGGraphicsElement {
};

4.13.6. Interface SVGDescElement

An SVGDescElement object represents a desc element in the DOM.

interface SVGDescElement : SVGElement {
};

4.13.7. Interface SVGMetadataElement

An SVGMetadataElement object represents a metadata element in the DOM.

interface SVGMetadataElement : SVGElement {
};

4.13.8. Interface SVGTitleElement

An SVGTitleElement object represents a title element in the DOM.

interface SVGTitleElement : SVGElement {
};

4.13.9. Interface SVGSymbolElement

An SVGSymbolElement object represents a symbol element in the DOM.

interface SVGSymbolElement : SVGElement {
};

SVGSymbolElement implements SVGFitToViewBox;

4.13.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;
};

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.

4.13.11. Interface SVGSwitchElement

An SVGSwitchElement object represents a switch element in the DOM.

interface SVGSwitchElement : SVGGraphicsElement {
};

4.13.12. 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.

SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

Chapter 5: Styling

5.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.

5.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:
None
Content model:
Any elements or 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.

5.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-SS].

5.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.

5.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>

5.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, 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 properties supported by an implementation have a corresponding presentation attribute. Attributes of the same name on other elements must not be parsed as a presentation attribute and will not affect CSS cascading and inheritance. Also, only elements in the SVG namespace support presentation attributes. Presentation attributes may be set on any element where there is not a name clash with an existing attribute or property.

Properties with a presentation attribute Elements that support the presentation attribute
cx, cy circle and ellipse
height, width, x, y foreignObject, image, mask, rect and svg
r circle
rx, ry ellipse and rect
d path and textPath
alignment-baseline, baseline-shift, clip, clip-path, clip-rule, color, color-interpolation, color-interpolation-filters, color-rendering, cursor, direction, display, dominant-baseline, fill, 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, transform, 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 ‘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.

The following table lists the presentation attributes whose names are different from their corresponding property. All other presentation attributes have names that do match their property.

PropertyElementPresentation attribute name
transformlinearGradient and radialGradient‘gradientTransform’
transformpattern‘patternTransform’

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.

5.7. Required properties

The following properties must be supported by all SVG user agents:

5.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;
}

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). [CSS3TRANSFORMS]

5.9. Required CSS features

Besides the features described above, the following CSS features must be also supported in SVG user agents:

5.10. DOM interfaces

5.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.

SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

Chapter 6: 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.

6.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.

6.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.

6.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.

6.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.

6.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.

6.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.

6.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.

6.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 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.

SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

Chapter 7: Coordinate Systems, Transformations and Units

7.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.

7.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 vb-x - e-x.
  10. Initialize translate-y to vb-y - e-y.
  11. If align contains 'xMid', add (e-width - vb-width * scale-x) / 2 to transform-x.
  12. If align contains 'xMax', add (e-width - vb-width * scale-x) to transform-x.
  13. If align contains 'yMid', add (e-height - vb-height * scale-y) / 2 to transform-y.
  14. If align contains 'yMax', add (e-height - vb-height * scale-y) to transform-y.

The transform applied to content contained by the element is given by translate(translate-x, translate-y) scale(scale-x, scale-y).

7.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>

7.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 ([CSS21], 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 [CSS21] 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 ([CSS21], 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)

7.5. The ‘transform’ property

User agents must support the transform property and presentation attribute as defined in [CSS3TRANSFORMS].

7.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 (see Error processing). 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.

7.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

7.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:

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.

7.9. Units

SVG follows the description and definition of common values and units from the CSS Values and Units Module [CSS3VALUES] 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.

7.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 example, for horizontal text, the calculations must assume that each glyph extends vertically to the full ascent and descent values for the font. An exception to this is when the inline-size presentation attribute has been specified on the text element, in which case the element's content area is its bounding box.

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:

Need to define what the union of rectangles with no area means.

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.

    Need to update this take into account inline-size on text.

  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 tighest 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 has an ancestor element within parent 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 and the same values for space, fill, stroke, markers and clipped as the corresponding algorithm input values.
  4. Return box.
canvas
foreignObject
iframe
image
video
  1. Return the tightest rectangle in coordinate space space that contains the rectangle defined by the ‘x’, ‘y’, ‘width’ and ‘height’ attributes of the element.

    The fill, stroke and markers input arguments to this algorithm do not affect the bounding box returned for these elements.

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.

7.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.
mesh 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 as a graphics object (i.e., not as a paint server) 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.

7.12. Intrinsic sizing properties of the SVG viewport of SVG content

SVG needs to specify how to calculate some intrinsic sizing properties to enable inclusion within other host documents. The intrinsic width and height of the SVG viewport of SVG content must be determined from the width and height properties. If either of these are not specified, the used value is the initial value 'auto'. Specifically, percentage values do not provide an intrinsic width or height.

We have the problem that either width and height are

Furthermore we can have a intrinsic ratio with viewBox. We need to describe all combinations and what happens in these cases in detail. The current text does not seem sufficient enough to describe all cases.

The outcome of this should be a intrinsic ratio for all cases.

The intrinsic aspect ratio of the SVG viewport of SVG content is necessary for example, when including SVG from an ‘object’ element in HTML styled with CSS. It is possible (indeed, common) for an SVG graphic to have an intrinsic aspect ratio but not to have an intrinsic width or height. The intrinsic aspect ratio must be calculated based upon the following rules:

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.

7.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 introduces 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.

Name: vector-effect
Value: none | [ non-scaling-stroke | non-scaling-size | non-rotation | fixed-position ]+ [ viewport | screen ]?
Initial: none
Applies to: graphics elements
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.

7.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 normal coordinate transformation formula from local coordinate system to viewport coordinate system is as follows.

The code assumes a 2D rendering context. Width CSS Transforms we get a 3D rendering context as well? How does that work on perspective or 3D transformations?
CSS Transforms Level 1 mentions about 3D rendering context and non scaling stroke with the purport that the functionality becomes no affect. Is it appropriate to extend it to all the vector effects?

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

7.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

7.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"/>

7.14. DOM interfaces

7.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.

7.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.

7.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.

7.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.

7.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.

SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

Chapter 8: Paths

8.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.)

8.2. The ‘path’ element

path
Categories:
Graphics element, markable element, renderable element, shape element
Content model:
Any number of the following elements, in any order:clipPath, marker, mask, script
Attributes:
Geometry properties:
DOM Interfaces:

The outline of a shape for a path element is specified using the d property. See Path data below.

8.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

8.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 path data are as follows:

The path data syntax is a prefix notation (i.e., commands followed by parameters). The only allowable decimal point is a Unicode U+0046 FULL STOP (".") character (also referred to in Unicode as PERIOD, dot and decimal point) and no other delimiter characters are allowed [UNICODE]. (For example, the following is an invalid numeric value in a path data stream: "13,000.56". Instead, say: "13000.56".)

For the relative versions of the commands, all coordinate values are relative to the current point at the start of the command.

Relative path commands are also influenced by the current bearing, which is an angle set by the bearing commands. This allows for paths to be specified using a style of "turtle graphics", where straight line and curved path segments are placed with their starting point at a tangent (or at some other angle) to the current bearing.

In the tables below, the following notation is used to describe the syntax of a given path command:

In the description of the path commands, cpx and cpy represent the coordinates of the current point, and cb represents the current bearing.

8.3.2. Specifying path data: the ‘d’ property

Name: d
Value: none | path(<string>)
Initial: none
Applies to: path
Inherited: no
Percentages: N/A
Media: visual
Computed value: as specified
Animatable: yes

The d property is used to specify the shape of a path element.

The value none indicates that there is no path data for the element. For path elements, this means that the element does not render or contribute to the bounding box of ancestor container elements.

A path is made up of multiple segments, and every command, either explicit or implicit, other than moveto or closepath, defines one path segment.

All coordinates and lengths specified within path data must be treated as being in user units in the current user coordinate system.

The path(<string>) value specifies a shape using a path data string. The contents of the <string> value must match the svg-path EBNF grammar defined below, and errors within the string are handled according to the rules in the Path Data Error Handling section. If the path data string contains no valid commands, then the behavior is the same as the none value.

While the d property takes the above values, the ‘d’ presentation attribute for the path element instead accepts path data string contents without the surrounding path("...") function and string quotes.

For example, the following two path definitions are equivalent:

<path style="d: path('M 100,100 L 200,200');"/>
<path d="M 100,100 L 200,200"/>

For animation, two d property values can only be interpolated smoothly when they both are path(...) values and the path data strings contain exactly the number and types of path data commands. If an animation is specified and the lists of path data commands are not the same, then the values must be interpolated using the discrete animation type.

If the list of path data commands are the same, then each parameter to each path data command must be interpolated separately as real numbers. Flags and booleans must be interpolated as fractions between zero and one, with any non-zero value considered to be a value of one/true.

The following sections list the commands that canbe used in path data strings. Those that draw straight line segments include the lineto commands (L, l, H, h, V and v) and the close path commands (Z and z). These three groups of commands draw curves:

8.3.3. The "moveto" commands

The "moveto" commands (M or m) must establish a new initial point and a new current point. The effect is as if the "pen" were lifted and moved to a new location. A path data segment (if there is one) must begin with a "moveto" command. Subsequent "moveto" commands (i.e., when the "moveto" is not the first command) represent the start of a new subpath:

Command Name Parameters Description
M (absolute)
m (relative)
moveto (x y)+ Start a new sub-path at the given (x,y) coordinates. M (uppercase) indicates that absolute coordinates will follow; m (lowercase) indicates that relative coordinates will follow. If a moveto is followed by multiple pairs of coordinates, the subsequent pairs are treated as implicit lineto commands. Hence, implicit lineto commands will be relative if the moveto is relative, and absolute if the moveto is absolute. If a relative moveto (m) appears as the first element of the path, then it is treated as a pair of absolute coordinates. In this case, subsequent pairs of coordinates are treated as relative even though the initial moveto is interpreted as an absolute moveto.

When a relative m command is used, the position moved to is (cpx + x cos cb + y sin cb, cpy + x sin cb + y cos cb).

8.3.4. The "closepath" command

The "closepath" (Z or z) must end the current subpath by connecting it back to its initial point in either of two ways:

  1. If the previous command is complete, that is that all the required coordinate data has been supplied, then an automatic straight line must be drawn from the current point to the initial point of the current subpath. This path segment may be of zero length.
  2. If the previous command is a "lineto", "curveto", "smooth curveto", "quadratic Bézier curveto", "smooth quadratic Bézier curveto", or "elliptical arc", that is missing required coordinate data, then the initial point must be used in place of each missing (x,y) coordinate.
Command Name Parameters Description
Z or
z
closepath (none) Close the current subpath by connecting it back to the current subpath's initial point (see prose above). Since the Z and z commands take no parameters, they have an identical effect.

SVG 2 adds the ability to fill in missing coordinate data with the Z or z command to avoid the need to add a zero length (or very short in the case of relative paths with rounding errors) path segment to close a subpath. This can effect the number of markers drawn and their orientation at the beginning/end of a closed subpath.

The use of Z or z to replace missing coordinate data with the coordinate of the initial point in a subpath was resolved at the Sydney (2015) meeting.

A closed subpath must be closed with a "closepath" command, this "joins" the first and last path segments. Any other path is an open subpath.

A closed subpath differs in behavior from an open subpath whose final coordinate is the initial point of the subpath. The first and last path segments of an open subpath will not be joined, even when the final coordinate of the last path segment is the initial point of the subpath. This will result in the first and last path segments being capped using the current value of stroke-linecap rather than joined using the current value of stroke-linejoin.

If a "closepath" is followed immediately by a "moveto", then the "moveto" identifies the start point of the next subpath. If a "closepath" is followed immediately by any other command, then the next subpath must start at the same initial point as the current subpath.

The current bearing does not affect a z command.

Examples:

8.3.5. The "lineto" commands

The various "lineto" commands draw straight lines from the current point to a new point:

Command Name Parameters Description
L (absolute)
l (relative)
lineto (x y)+ Draw a line from the current point to the given (x,y) coordinate which becomes the new current point. L (uppercase) indicates that absolute coordinates will follow; l (lowercase) indicates that relative coordinates will follow. A number of coordinates pairs may be specified to draw a polyline. At the end of the command, the new current point is set to the final set of coordinates provided.
H (absolute)
h (relative)
horizontal lineto x+ Draws a horizontal line from the current point. H (uppercase) indicates that absolute coordinates will follow; h (lowercase) indicates that relative coordinates will follow. Multiple x values can be provided (although usually this doesn't make sense). An H or h command is equivalent to an L or l command with 0 specified for the y coordinate. At the end of the command, the new current point is taken from the final coordinate value.
V (absolute)
v (relative)
vertical lineto y+ Draws a vertical line from the current point. V (uppercase) indicates that absolute coordinates will follow; v (lowercase) indicates that relative coordinates will follow. Multiple y values can be provided (although usually this doesn't make sense). A V or v command is equivalent to an L or l command with 0 specified for the x coordinate. At the end of the command, the new current point is taken from the final coordinate value.

When a relative l command is used, the end point of the line is (cpx + x cos cb + y sin cb, cpy + x sin cb + y cos cb).

When a relative h command is used, the end point of the line is (cpx + x cos cb, cpy + x sin cb). This means that an h command with a positive x value draws a line in the direction of the current bearing. When the current bearing is 0, this is a horizontal line in the direction of the positive x-axis.

When there is a non-zero bearing, a mnemonic for the h command could be "head this distance at the current bearing", rather than "draw a horizontal line".

When a relative v command is used, the end point of the line is (cpx + y sin cb, cpy + y cos cb).

8.3.6. The cubic Bézier curve commands

The cubic Bézier commands are as follows:

Command Name Parameters Description
C (absolute)
c (relative)
curveto (x1 y1 x2 y2 x y)+ Draws a cubic Bézier curve from the current point to (x,y) using (x1,y1) as the control point at the beginning of the curve and (x2,y2) as the control point at the end of the curve. C (uppercase) indicates that absolute coordinates will follow; c (lowercase) indicates that relative coordinates will follow. Multiple sets of coordinates may be specified to draw a polybézier. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybézier.
S (absolute)
s (relative)
shorthand/smooth curveto (x2 y2 x y)+ Draws a cubic Bézier curve from the current point to (x,y). The first control point is assumed to be the reflection of the second control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not an C, c, S or s, assume the first control point is coincident with the current point.) (x2,y2) is the second control point (i.e., the control point at the end of the curve). S (uppercase) indicates that absolute coordinates will follow; s (lowercase) indicates that relative coordinates will follow. Multiple sets of coordinates may be specified to draw a polybézier. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybézier.

When a relative c or s command is used, each of the relative coordinate pairs is computed as for those in an m command. For example, the final control point of the curve of both commands is (cpx + x cos cb + y sin cb, cpy + x sin cb + y cos cb).

Example cubic01 shows some simple uses of cubic Bézier commands within a path. The example uses an internal CSS style sheet to assign styling properties. Note that the control point for the "S" command is computed automatically as the reflection of the control point for the previous "C" command relative to the start point of the "S" command.

<?xml version="1.0" standalone="no"?>
<svg width="5cm" height="4cm" viewBox="0 0 500 400"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
  <title>Example cubic01- cubic Bézier commands in path data</title>
  <desc>Picture showing a simple example of path data
        using both a "C" and an "S" command,
        along with annotations showing the control points
        and end points</desc>
  <style type="text/css"><![CDATA[
    .Border { fill:none; stroke:blue; stroke-width:1 }
    .Connect { fill:none; stroke:#888888; stroke-width:2 }
    .SamplePath { fill:none; stroke:red; stroke-width:5 }
    .EndPoint { fill:none; stroke:#888888; stroke-width:2 }
    .CtlPoint { fill:#888888; stroke:none }
    .AutoCtlPoint { fill:none; stroke:blue; stroke-width:4 }
    .Label { font-size:22; font-family:Verdana }
  ]]></style>

  <rect class="Border" x="1" y="1" width="498" height="398" />

  <polyline class="Connect" points="100,200 100,100" />
  <polyline class="Connect" points="250,100 250,200" />
  <polyline class="Connect" points="250,200 250,300" />
  <polyline class="Connect" points="400,300 400,200" />
  <path class="SamplePath" d="M100,200 C100,100 250,100 250,200
                                       S400,300 400,200" />
  <circle class="EndPoint" cx="100" cy="200" r="10" />
  <circle class="EndPoint" cx="250" cy="200" r="10" />
  <circle class="EndPoint" cx="400" cy="200" r="10" />
  <circle class="CtlPoint" cx="100" cy="100" r="10" />
  <circle class="CtlPoint" cx="250" cy="100" r="10" />
  <circle class="CtlPoint" cx="400" cy="300" r="10" />
  <circle class="AutoCtlPoint" cx="250" cy="300" r="9" />
  <text class="Label" x="25" y="70">M100,200 C100,100 250,100 250,200</text>
  <text class="Label" x="325" y="350"
        style="text-anchor:middle">S400,300 400,200</text>
</svg>
Example cubic01 — cubic Bézier comamnds in path data

Example cubic01

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

The following picture shows some how cubic Bézier curves change their shape depending on the position of the control points. The first five examples illustrate a single cubic Bézier path segment. The example at the lower right shows a "C" command followed by an "S" command.

Example cubic02 - cubic Bézier commands in path data

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

8.3.7. The quadratic Bézier curve commands

The quadratic Bézier commands are as follows:

Command Name Parameters Description
Q (absolute)
q (relative)
quadratic Bézier curveto (x1 y1 x y)+ Draws a quadratic Bézier curve from the current point to (x,y) using (x1,y1) as the control point. Q (uppercase) indicates that absolute coordinates will follow; q (lowercase) indicates that relative coordinates will follow. Multiple sets of coordinates may be specified to draw a polybézier. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybézier.
T (absolute)
t (relative)
Shorthand/smooth quadratic Bézier curveto (x y)+ Draws a quadratic Bézier curve from the current point to (x,y). The control point is assumed to be the reflection of the control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not a Q, q, T or t, assume the control point is coincident with the current point.) T (uppercase) indicates that absolute coordinates will follow; t (lowercase) indicates that relative coordinates will follow. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybézier.

When a relative q or t command is used, each of the relative coordinate pairs is computed as for those in an m command. For example, the final control point of the curve of both commands is (cpx + x cos cb + y sin cb, cpy + x sin cb + y cos cb).

Example quad01 shows some simple uses of quadratic Bézier commands within a path. Note that the control point for the "T" command is computed automatically as the reflection of the control point for the previous "Q" command relative to the start point of the "T" command.

<?xml version="1.0" standalone="no"?>
<svg width="12cm" height="6cm" viewBox="0 0 1200 600"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
  <title>Example quad01 - quadratic Bézier commands in path data</title>
  <desc>Picture showing a "Q" a "T" command,
        along with annotations showing the control points
        and end points</desc>
  <rect x="1" y="1" width="1198" height="598"
        fill="none" stroke="blue" stroke-width="1" />

  <path d="M200,300 Q400,50 600,300 T1000,300"
        fill="none" stroke="red" stroke-width="5"  />
  <!-- End points -->
  <g fill="black" >
    <circle cx="200" cy="300" r="10"/>
    <circle cx="600" cy="300" r="10"/>
    <circle cx="1000" cy="300" r="10"/>
  </g>
  <!-- Control points and lines from end points to control points -->
  <g fill="#888888" >
    <circle cx="400" cy="50" r="10"/>
    <circle cx="800" cy="550" r="10"/>
  </g>
  <path d="M200,300 L400,50 L600,300 
           L800,550 L1000,300"
        fill="none" stroke="#888888" stroke-width="2" />
</svg>
Example quad01 — quadratic Bézier commands in path data

Example quad01

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

8.3.8. The elliptical arc curve commands

SVG 2 Requirement: Make it simpler to draw arcs in SVG path syntax.
Resolution: Make arcs in paths easier.
Purpose: To make it easier for authors to write path data with arcs by hand.
Owner: Cameron (ACTION-3151)

The elliptical arc commands are as follows:

Command Name Parameters Description
A (absolute)
a (relative)
elliptical arc (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ Draws an elliptical arc from the current point to (x, y). The size and orientation of the ellipse are defined by two radii (rx, ry) and an x-axis-rotation, which indicates how the ellipse as a whole is rotated, in degrees, relative to the current coordinate system. The center (cx, cy) of the ellipse is calculated automatically to satisfy the constraints imposed by the other parameters. large-arc-flag and sweep-flag contribute to the automatic calculations and help determine how the arc is drawn.

When a relative a command is used, the end point of the arc is (cpx + x cos cb + y sin cb, cpy + x sin cb + y cos cb). The effective value of the x-axis-rotation parameter is also affected by the current bearing: it is computed as x-axis-rotation + cb.

Example arcs01 shows some simple uses of arc commands within a path.

<?xml version="1.0" standalone="no"?>
<svg width="12cm" height="5.25cm" viewBox="0 0 1200 400"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
  <title>Example arcs01 - arc commands in path data</title>
  <desc>Picture of a pie chart with two pie wedges and
        a picture of a line with arc blips</desc>
  <rect x="1" y="1" width="1198" height="398"
        fill="none" stroke="blue" stroke-width="1" />

  <path d="M300,200 h-150 a150,150 0 1,0 150,-150 z"
        fill="red" stroke="blue" stroke-width="5" />
  <path d="M275,175 v-150 a150,150 0 0,0 -150,150 z"
        fill="yellow" stroke="blue" stroke-width="5" />

  <path d="M600,350 l 50,-25 
           a25,25 -30 0,1 50,-25 l 50,-25 
           a25,50 -30 0,1 50,-25 l 50,-25 
           a25,75 -30 0,1 50,-25 l 50,-25 
           a25,100 -30 0,1 50,-25 l 50,-25"
        fill="none" stroke="red" stroke-width="5"  />
</svg>
Example arcs01 — arc commands in path data

Example arcs01

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

The elliptical arc command draws a section of an ellipse which must meet the following constraints:

For most situations, there are actually four different arcs (two different ellipses, each with two different arc sweeps) that satisfy these constraints. large-arc-flag and sweep-flag indicate which one of the four arcs are drawn, as follows:

The following illustrates the four combinations of large-arc-flag and sweep-flag and the four different arcs that will be drawn based on the values of these flags. For each case, the following path data command was used:

<path d="M 125,75 a100,50 0 ?,? 100,50"
      style="fill:none; stroke:red; stroke-width:6"/>

where "?,?" is replaced by "0,0" "0,1" "1,0" and "1,1" to generate the four possible cases.

Illustration of flags in arc commands

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

Refer to Elliptical arc implementation notes for detailed implementation notes for the path data elliptical arc commands.

8.3.9. The bearing commands

The bearing commands are at risk, with no known implementations.

The bearing commands (B or b) set the current bearing, which influences the orientation of subsequent relative path commands:

Command Name Parameters Description
B (absolute)
b (relative)
bearing angle+ Sets the current bearing. The parameter is an angle in degrees, where 0 indicates the direction of the positive x-axis. B (uppercase) sets the current bearing to the specified angle; b (lowercase) sets the current bearing to be the angle of the tangent at the end of the preceding path command plus the specified angle. The current point is unaffected. Although multiple parameters may be specified, this usually will not be useful, as they could be combined into a single angle value.

At the beginning of a path, the current bearing is 0, which points in the direction of the positive x-axis. The current bearing remains unchanged until a B or b command is encountered. Since the relative b command sets the current bearing relative to the tangent at the end of the preceding path command, it is possible to set the bearing to that tangent by using "b 0".

The example below shows how bearing commands can be used to draw a regular pentagon.

<svg xmlns="http://www.w3.org/2000/svg"
     width="300" height="100" viewBox="0 0 300 100">

  <path fill="#eee"
        stroke="deeppink" stroke-width="8px" stroke-linejoin="round"
        d="M 150,10
           B 36 h 47
           b 72 h 47
           b 72 h 47
           b 72 h 47 z"/>

</svg>
Image showing the use of the bearing command.

Bearing commands can be used to position the end points of the sides of a regular polygon without having to use trigonometry to calculate them based on the polygon's interior angles.

8.3.10. The grammar for path data

SVG path data matches the following EBNF grammar.

svg_path::= wsp* moveto? (moveto drawto_command*)?

drawto_command::=
    moveto
    | closepath
    | lineto
    | horizontal_lineto
    | vertical_lineto
    | curveto
    | smooth_curveto
    | quadratic_bezier_curveto
    | smooth_quadratic_bezier_curveto
    | elliptical_arc
    | bearing

moveto::=
    ( "M" | "m" ) wsp* coordinate_pair_sequence wsp* closepath?

closepath::= 
    ("Z" | "z")

lineto::=
    ("L"|"l") wsp* (coordinate_pair_sequence | closepath)

horizontal_lineto::=
    ("H"|"h") wsp* coordinate_sequence

vertical_lineto::=
    ("V"|"v") wsp* coordinate_sequence

curveto::=
    ("C"|"c") wsp* (curveto_coordinate_sequence | (coordinate_pair_sequence? closepath))

curveto_coordinate_sequence::=
    coordinate_pair_triplet
    | (coordinate_pair_triplet comma_wsp? curveto_coordinate_sequence)

smooth_curveto::=
    ("S"|"s") wsp* (smooth_curveto_coordinate_sequence
    | (coordinate_pair_sequence? closepath))

smooth_curveto_coordinate_sequence::=
    coordinate_pair_double
    | (coordinate_pair_double comma_wsp? smooth_curveto_coordinate_sequence)

quadratic_bezier_curveto::=
    ("Q"|"q") wsp*
    (quadratic_bezier_curveto_coordinate_sequence | (coordinate_pair_sequence? closepath))

quadratic_bezier_curveto_coordinate_sequence::=
    coordinate_pair_double
    | (coordinate_pair_double comma_wsp? quadratic_bezier_curveto_coordinate_sequence)

smooth_quadratic_bezier_curveto::=
    ("T"|"t") wsp* (coordinate_pair_sequence | closepath)

elliptical_arc::=
    ( "A" | "a" ) wsp*
    (elliptical_arc_argument_sequence
    | (elliptical_arc_argument_sequence? elliptical_arc_closing_argument))

elliptical_arc_argument_sequence::=
    elliptical_arc_argument
    | (elliptical_arc_argument comma_wsp? elliptical_arc_argument_sequence)

elliptical_arc_argument::=
    number comma_wsp? number comma_wsp? number comma_wsp
    flag comma_wsp? flag comma_wsp? coordinate_pair

elliptical_arc_closing_argument::=
    number comma_wsp? number comma_wsp? number comma_wsp
    flag comma_wsp? flag comma_wsp? closepath

bearing::=
    ( "B" | "b" ) wsp* bearing_argument_sequence

bearing_argument_sequence::=
    number | (number comma_wsp? bearing_argument_sequence)

coordinate_pair_double::=
    coordinate_pair comma_wsp? coordinate_pair

coordinate_pair_triplet::=
    coordinate_pair comma_wsp? coordinate_pair comma_wsp? coordinate_pair

coordinate_pair_sequence::=
    coordinate_pair | (coordinate_pair comma_wsp? coordinate_pair_sequence)

coordinate_sequence::=
    coordinate | (coordinate comma_wsp? coordinate_sequence)

coordinate_pair::= coordinate comma_wsp? coordinate

coordinate::= sign? number

sign::= "+"|"-"
number ::= ([0-9])+
flag::=("0"|"1")
comma_wsp::=(wsp+ ","? wsp*) | ("," wsp*)
wsp ::= (#x9 | #x20 | #xA | #xC | #xD)

The processing of the EBNF must consume as much of a given EBNF production as possible, stopping at the point when a character is encountered which no longer satisfies the production. Thus, in the string "M 100-200", the first coordinate for the "moveto" consumes the characters "100" and stops upon encountering the minus sign because the minus sign cannot follow a digit in the production of a "coordinate". The result is that the first coordinate will be "100" and the second coordinate will be "-200".

Similarly, for the string "M 0.6.5", the first coordinate of the "moveto" consumes the characters "0.6" and stops upon encountering the second decimal point because the production of a "coordinate" only allows one decimal point. The result is that the first coordinate will be "0.6" and the second coordinate will be ".5".

Note that the EBNF allows the path data string in the d property to be empty. This is not an error, instead it disables rendering of the path. Rendering is also disabled when the d property has the value none.

If path data not matching the grammar is encountered, then the path data is in error (see Error Handling).

8.4. Path directionality

Some features, such as the orientation of markers and the shapes of line caps, are defined in terms of the direction of the path at a given distance along the path or at the start or end of an individual segment.

The direction of a path at a specified distance along the path is defined as follows:

The direction at the start of a path segment is defined as follows:

The direction at the end of a path segment is defined as follows:

8.5. Implementation notes

8.5.1. Error handling in path data

A conforming SVG user agent must implement path rendering as follows:

8.6. Distance along a path

Various operations, including text on a path and motion animation and various stroke operations, require that the user agent compute the distance along the geometry of a graphics element, such as a path.

Exact mathematics exist for computing distance along a path, but the formulas are highly complex and require substantial computation. It is recommended that authoring products and user agents employ algorithms that produce as precise results as possible; however, to accommodate implementation differences and to help distance calculations produce results that approximate author intent, the pathLength attribute can be used to provide the author's computation of the total length of the path so that the user agent can scale distance-along-a-path computations by the ratio of pathLength to the user agent's own computed value for total path length.

A "moveto" or "bearing" operation within a path element is defined to have zero length. Only the various "lineto", "curveto" and "arcto" commands contribute to path length calculations.

8.6.1. The ‘pathLength’ attribute

Name Value Initial value Animatable
pathLength <number> (none) yes

The author's computation of the total length of the path, in user units. This value is used to calibrate the user agent's own distance-along-a-path calculations with that of the author. The user agent will scale all distance-along-a-path computations by the ratio of pathLength to the user agent's own computed value for total path length. pathLength potentially affects calculations for text on a path, motion animation and various stroke operations.

A value of zero is valid and must be treated as a scaling factor of infinity. A value of zero scaled infinitely must remain zero, while any value greater than zero must become +Infinity.

A negative value is an error (see Error handling).

8.7. DOM interfaces

8.7.1. Interface SVGPathElement

An SVGPathElement object represents a path in the DOM.

interface SVGPathElement : SVGGeometryElement {

};
SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

SVG 2 – 31 May 2016 TopContentsPreviousNextElementsAttributesProperties

Chapter 9: Basic Shapes

9.1. Introduction and definitions

basic shape
shape
shape elements
A graphics element that is defined by some combination of straight lines and curves. Specifically: circle, ellipse, line, path, polygon, polyline and rect.

SVG contains the following set of basic shape elements:

Mathematically, these shape elements are equivalent to a path element that would construct the same shape. The basic shapes may be stroked, filled and used as clip paths. All of the properties available for path elements also apply to the basic shapes.

The equivalent path and algorithm to compute the stroke for each shape are defined in the shape sections below.

9.2. The ‘rect’ element

The rect element defines a rectangle which is axis-aligned with the current local coordinate system. Rounded rectangles can be achieved by setting appropriate values for attributes rx and ry.

rect
Categories:
Graphics element, renderable element, shape element
Content model:
Any number of the following elements, in any order:clipPath, marker, mask, script
Attributes:
Geometry properties:
DOM Interfaces:

The x and y coordinates refer to the left and top edges of the rectangle, in the current user coordinate system.

The width and height of the rectangle. A negative value for either attribute is an error (see Error processing). A value of zero for either attribute disables rendering of the element.

For rounded rectangles, the x- and y-axis radii of the ellipse used to round off the corners of the rectangle. A negative value for either attribute is an error (see Error processing).

The values used for the x- and y-axis rounded corner radii are determined implicitly if the rx or ry attributes (or both) are not specified, or are specified but with invalid values. The values are also subject to clamping so that the lengths of the straight segments of the rectangle are never negative. The effective values for rx and ry are determined by following these steps in order:

  1. Let rx and ry be length values.
  2. If neither rx nor ry are properly specified, then set both rx and ry to 0. (This will result in square corners.)
  3. Otherwise, if a properly specified value is provided for rx, but not for ry, then set both rx and ry to the value of rx.
  4. Otherwise, if a properly specified value is provided for ry, but not for rx, then set both rx and ry to the value of ry.
  5. Otherwise, both rx and ry were specified properly. Set rx to the value of rx and ry to the value of ry.
  6. If rx is greater than half of width, then set rx to half of width.
  7. If ry is greater than half of height, then set ry to half of height.
  8. The effective values of rx and ry are rx and ry, respectively.

Mathematically, a rect element is mapped to an equivalent path element as follows: (Note: all coordinate and length values are first converted into local coordinate system coordinates according to Units.)

Path decomposition resolved during teleconference on June 3rd, 2013.

Example rect01 shows a rectangle with sharp corners. The rect element is filled with yellow and stroked with navy.

<?xml version="1.0" standalone="no"?>
<svg width="12cm" height="4cm" viewBox="0 0 1200 400"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
  <desc>Example rect01 - rectangle with sharp corners</desc>

  <!-- Show outline of viewport using 'rect' element -->
  <rect x="1" y="1" width="1198" height="398"
        fill="none" stroke="blue" stroke-width="2"/>

  <rect x="400" y="100" width="400" height="200"
        fill="yellow" stroke="navy" stroke-width="10"  />
</svg>
Example rect01 — rectangle with sharp corners

Example rect01

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

Example rect02 shows two rounded rectangles. The rx specifies how to round the corners of the rectangles. Note that since no value has been specified for the ry attribute, it will be assigned the same value as the rx attribute.

<?xml version="1.0" standalone="no"?>
<svg width="12cm" height="4cm" viewBox="0 0 1200 400"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
  <desc>Example rect02 - rounded rectangles</desc>

  <!-- Show outline of viewport using 'rect' element -->
  <rect x="1" y="1" width="1198" height="398"
        fill="none" stroke="blue" stroke-width="2"/>

  <rect x="100" y="100" width="400" height="200" rx="50"
        fill="green" />

  <g transform="translate(700 210) rotate(-30)">
    <rect x="0" y="0" width="400" height="200" rx="50"
          fill="none" stroke="purple" stroke-width="30" />
  </g>
</svg>
Example rect02 — rounded rectangles expressed in user coordinates

Example rect02

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

9.3. The ‘circle’ element

The circle element defines a circle based on a center point and a radius.

circle
Categories:
Graphics element, renderable element, shape element
Content model:
Any number of the following elements, in any order:clipPath, marker, mask, script
Attributes:
Geometry properties:
DOM Interfaces:

The cx and cy attributes define the coordinates of the center of the circle.

The r attribute defines the radius of the circle. A negative value is an error (see Error processing). A value of zero disables rendering of the element.

Mathematically, a circle element is mapped to an equivalent path element that consists of four elliptical arc segments, each covering a quarter of the circle. The path begins at the "3 o'clock" point on the radius and proceeds in a clock-wise direction (before any transformations).

Path decomposition resolved during teleconference on June 3rd, 2013.

Example circle01 consists of a circle element that is filled with red and stroked with blue.

<?xml version="1.0" standalone="no"?>
<svg width="12cm" height="4cm" viewBox="0 0 1200 400"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
  <desc>Example circle01 - circle filled with red and stroked with blue</desc>

  <!-- Show outline of viewport using 'rect' element -->
  <rect x="1" y="1" width="1198" height="398"
        fill="none" stroke="blue" stroke-width="2"/>

  <circle cx="600" cy="200" r="100"
        fill="red" stroke="blue" stroke-width="10"  />
</svg>
Example circle01 — circle filled with red and stroked with blue

Example circle01

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

9.4. The ‘ellipse’ element

The ellipse element defines an ellipse which is axis-aligned with the current local coordinate system based on a center point and two radii.

ellipse
Categories:
Graphics element, renderable element, shape element
Content model:
Any number of the following elements, in any order:clipPath, marker, mask, script
Attributes: