Copyright © 2013 W3C® (MIT, ERCIM, Keio, Beihang), All Rights Reserved. W3C liability, trademark and document use rules apply.
This specification defines the features and syntax for Scalable Vector Graphics (SVG) Version 2, a language for describing two-dimensional vector and mixed vector/raster graphics. Although an XML serialization is given, processing is defined in terms of a DOM.
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 18 June 2013 Working 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 Working 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:
In this Working Draft, by default, the background colors indicating section maturity are hidden and only annotations that record specific requirements for SVG 2 as part of our requirements gathering exercise are visible. To view the section maturity background colors and any additional annotations, the "All annotations" alternate style sheet can be used.
This document has been produced by the W3C SVG Working Group as part of the Graphics Activity within the W3C Interaction Domain. The goals of the W3C SVG Working Group are discussed in the W3C SVG Charter. The W3C SVG Working Group maintains a public Web page, 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.
The SVG Working Group would like to thank the following people for contributing to this specification by raising issues that resulted in changes: 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.
This specification defines the features and syntax for Scalable Vector Graphics (SVG).
SVG is a language for describing two-dimensional graphics in XML [XML10]. 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 into previously rendered objects. The feature set includes nested transformations, clipping paths, alpha masks, filter effects and template objects.
SVG drawings can be interactive and 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 such as ‘onmouseover’ and ‘onclick’ can be assigned to any SVG graphical object. Because of its compatibility and leveraging of other Web standards, features like scripting can be done on XHTML and SVG elements simultaneously within the same Web page.
SVG is a language for rich graphical content. For accessibility reasons, if there is an original source document containing higher-level structure and semantics, it is recommended that the higher-level information be made available somehow, either by making the original source document available, or making an alternative version available in an alternative format which conveys the higher-level information, or by using SVG's facilities to include the higher-level information within the SVG content. For suggested techniques in achieving greater accessibility, see Accessibility.
The MIME type for SVG is "image/svg+xml
" (see
XML Media Types
[RFC3023]). The
registration of this MIME type is in progress at the W3C.
It is recommended that SVG files have the extension
".svg"
(all lowercase) on all platforms. It is
recommended that gzip-compressed
[RFC1952]
SVG files have the extension ".svgz"
(all
lowercase) on all platforms.
Should we mention .svg.gz
?
It is recommended that SVG files stored on Macintosh HFS
file systems be given a file type of "svg "
(all lowercase, with a space character as the fourth letter).
It is recommended that gzip-compressed
SVG files stored on Macintosh HFS file systems be given a file
type of "svgz"
(all lowercase).
HFS file types are probably not relevant any more.
The SVG 2 namespace is http://www.w3.org/2000/svg
,
which is the same as for earlier versions of SVG.
A DTD is not provided in this specification, as the use of DTDs for validating XML documents is known to be problematic. In particular, DTDs do not handle namespaces gracefully. It is recommended that authors do not include a DOCTYPE declaration in SVG documents.
This section doesn't sound like it serves any real purpose other than self promotion for how well it utilizes other specifications and frameworks. I think it can be dropped, or at least condensed into a couple of sentences.
SVG leverages and integrates with other W3C specifications and standards efforts. By leveraging and conforming to other standards, SVG becomes more powerful and makes it easier for users to learn how to incorporate SVG into their Web sites.
The following describes some of the ways in which SVG maintains compatibility with, leverages and integrates with other W3C efforts:
The plan is to move away from XLink and use non-namespaced attributes for linking, while keeping ‘xlink:href’ for compatibility with existing content. Other unrelated XLink attributes like ‘xlink:role’ will be removed.
In environments which support DOM4 [DOM4] for other XML grammars (e.g., XHTML [XHTML]) and which also support SVG and the SVG DOM, a single scripting approach can be used simultaneously for both XML documents and SVG graphics, in which case interactive and dynamic effects will be possible on multiple XML namespaces using the same set of scripts.
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. These recommendations are not normative and conformance with this specification does not depend on their realization. These recommendations contain the expression "We recommend ...", "This specification recommends ...", or some similar wording.
Does it make sense to have a glossary here? How useful is it compared to defining terms where they make most sense in the body of the specification?
There should be a separate section that lists element and attribute categories and their members.
Need a definition, which can probably be ported over from SVG Tiny 1.2.
Should gradient elements also be context elements?
Need a definition, which can probably be ported over from SVG Tiny 1.2.
pointer-events
’ property.Provide an appropriate definition. This legalese sounding term comes from SVG 1.2 Tiny. A search for "lacuna value" results in the SVG 1.2 Tiny and the proto-SVG 2 specs (of February 2010).
An SVG context is a document fragment where all elements within the fragment must be subject to processing by an SVG user agent according to the rules in this specification.
If SVG content is embedded inline within parent XML (such as XHTML), the SVG context does not include the ancestors above the rootmost ‘svg’ element. If the SVG content contains any ‘foreignObject’ elements which in turn contain non-SVG content, the SVG context does not include the contents of the ‘foreignObject’ elements.
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.
This chapter is a bit waffley. How much of this do we really need to say?
SVG stands for Scalable Vector Graphics, an XML grammar for stylable graphics, usable as an XML namespace.
To be scalable means to increase or decrease uniformly. In terms of graphics, scalable means not being limited to a single, fixed, pixel size. On the Web, scalable means that a particular technology can grow to a large number of files, a large number of users, a wide variety of applications. SVG, being a graphics technology for the Web, is scalable in both senses of the word.
SVG graphics are scalable to different display resolutions, so that for example printed output uses the full resolution of the printer and can be displayed at the same size on screens of different resolutions. The same SVG graphic can be placed at different sizes on the same Web page, and re-used at different sizes on different pages. SVG graphics can be magnified to see fine detail, or to aid those with low vision.
SVG graphics are scalable because the same SVG content can be a stand-alone graphic or can be referenced or included inside other SVG graphics, thereby allowing a complex illustration to be built up in parts, perhaps by several people. The symbol, marker and font capabilities promote re-use of graphical components, maximize the advantages of HTTP caching and avoid the need for a centralized registry of approved symbols.
Vector graphics contain geometric objects such as lines and curves. This gives greater flexibility compared to raster-only formats (such as PNG and JPEG) which have to store information for every pixel of the graphic. Typically, vector formats can also integrate raster images and can combine them with vector information such as clipping paths to produce a complete illustration; SVG is no exception.
Since all modern displays are raster-oriented, the difference between raster-only and vector graphics comes down to where they are rasterized; client side in the case of vector graphics, as opposed to already rasterized on the server. SVG gives control over the rasterization process, for example to allow anti-aliased artwork without the ugly aliasing typical of low quality vector implementations. SVG also provides client-side raster filter effects, so that moving to a vector format does not mean the loss of popular effects such as soft drop shadows.
Most existing XML grammars represent either textual information, or represent raw data such as financial information. They typically provide only rudimentary graphical capabilities, often less capable than the HTML 'img' element. SVG fills a gap in the market by providing a rich, structured description of vector and mixed vector/raster graphics; it can be used stand-alone, or as an XML namespace with other grammars.
XML, a for structured information exchange, has become extremely popular and is both widely and reliably implemented. By being written in XML, SVG builds on this strong foundation and gains many advantages such as a sound basis for internationalization, powerful structuring capability, an object model, and so on. By building on existing, cleanly-implemented specifications, XML-based grammars are open to implementation without a huge reverse engineering effort.
It is certainly useful to have a stand-alone, SVG-only viewer. But SVG is also intended to be used as one component in a multi-namespace XML application. This multiplies the power of each of the namespaces used, to allow innovative new content to be created. For example, SVG graphics may be included in a document which uses any text-oriented XML namespace - including XHTML. A scientific document, for example, might also use MathML for mathematics in the document. The combination of SVG and SMIL leads to interesting, time based, graphically rich presentations.
SVG is a good, general-purpose component for any multi-namespace grammar that needs to use graphics.
The advantages of style sheets in terms of presentational control, flexibility, faster download and improved maintenance are now generally accepted, certainly for use with text. SVG extends this control to the realm of graphics.
The combination of scripting, DOM and CSS is often termed "Dynamic HTML" and is widely used for animation, interactivity and presentational effects. SVG allows the same script-based manipulation of the document tree and the style sheet.
With any XML grammar, consideration has to be given to what exactly is being modelled. For textual formats, modelling is typically at the level of paragraphs and phrases, rather than individual nouns, adverbs, or phonemes. Similarly, SVG models graphics at the level of graphical objects rather than individual points.
SVG provides a general path element, which can be used to create a huge variety of graphical objects, and also provides common basic shapes such as rectangles and ellipses. These are convenient for hand coding and may be used in the same ways as the more general path element. SVG provides fine control over the coordinate system in which graphical objects are defined and the transformations that will be applied during rendering.
It would have been possible to define some standard symbols that SVG would provide. But which ones? There would always be additional symbols for electronics, cartography, flowcharts, etc., that people would need that were not provided until the "next version". SVG allows users to create, re-use and share their own symbols without requiring a centralized registry. Communities of users can create and refine the symbols that they need, without having to ask a committee. Designers can be sure exactly of the graphical appearance of the symbols they use and not have to worry about unsupported symbols.
Symbols may be used at different sizes and orientations, and can be restyled to fit in with the rest of the graphical composition.
Many existing Web graphics use the filtering operations found in paint packages to create blurs, shadows, lighting effects and so on. With the client-side rasterization used with vector formats, such effects might be thought impossible. SVG allows the declarative specification of filters, either singly or in combination, which can be applied on the client side when the SVG is rendered. These are specified in such a way that the graphics are still scalable and displayable at different resolutions.
Graphically rich material is often highly dependent on the particular font used and the exact spacing of the glyphs. In many cases, designers convert text to outlines to avoid any font substitution problems. This means that the original text is not present and thus searchability and accessibility suffer. In response to feedback from designers, SVG includes font elements so that both text and graphical appearance are preserved.
Animation can be produced via script-based manipulation of the document, but scripts are difficult to edit and interchange between authoring tools is harder. Again in response to feedback from the design community, SVG includes declarative animation elements which were designed collaboratively by the SVG and SYMM Working Groups. This allows the animated effects common in existing Web graphics to be expressed in SVG.
We should reference the SVG Integration specification here, once that has been published.
There are a variety of ways in which SVG content can be included within a Web page. Here are some of the options:
image/svg+xml
") is loaded directly
into a user agent such as a Web browser. The SVG document is
the Web page that is presented to the user.HTML5 doesn't have longdesc; we should reference the appropriate aria attributes.
SVG 2 Requirement: Support the z-index.
Resolution: We will add Jonathan Watt's z-index proposal to SVG 2.
Purpose: Allow reordering (such as when a planet orbits the sun). Reordering without script support (e.g. CSS :hover).
Owner: Jonathan (Action 3002).
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).
Implementations of SVG are expected to behave as though they implement a rendering (or imaging) model corresponding to the one described in this chapter. A real implementation is not required to implement the model in this way, but the result on any device supported by the implementation shall match that described by this model.
The appendix on conformance requirements describes the extent to which an actual implementation may deviate from this description. In practice an actual implementation will 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).
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.
Elements in an SVG document fragment have an implicit drawing order, with the first elements in the SVG document fragment getting "painted" first. Subsequent elements are painted on top of previously painted elements.
Grouping elements, such as the ‘g’ element (see container elements) create a compositing group. The compositing group will composite and blend with the group backdrop with behaviour depending on the values of the compositing and blending properties, such as knock-out, and isolation. See Compositing and Blending Specification.
Individual graphics elements are rendered as if each graphics element represented its own compositing group; thus, the effect is as if a temporary separate canvas is created for each graphics element. The element is first painted onto the temporary canvas (see Painting shapes and text and Painting raster images below). Then any filter effects specified for the graphics element are applied to create a modified temporary canvas. The modified temporary canvas is then composited into the background, taking into account any clipping, masking and object opacity settings on the graphics element.
SVG supports three fundamental types of graphics elements that can be rendered onto the canvas:
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). A stroke operation is centered on the outline of the object; thus, in effect, half of the paint falls on the interior of the shape and half of the paint falls outside 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 selected vertices. 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 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.
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.
The fill and stroke operations are entirely independent painting operations; thus, if you both fill and stroke a shape, half of the stroke will be painted on top of part of the fill.
SVG supports the following built-in types of paint which can be used in fill and stroke operations:
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.
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.
SVG allows any painting operation to be limited to a subregion of the output device by clipping and masking. This is described in Clipping, Masking and Compositing.
Clipping uses a path to define a region of the output device
to which paint can be applied. Any painting operation executed
within the scope of the clipping must be rendered such that
only those parts of the device that fall within the clipping
region are affected by the painting operation. A clipping path
can be thought of as a mask wherein those pixels outside the
clipping path are black with an alpha value of zero and those
pixels inside the clipping path are white with an alpha value
of one. "Within" is defined by the same rules used to determine
the interior of a path for painting. The clipping path is
typically anti-aliased on low-resolution devices (see
‘shape-rendering
’. Clipping is
described in
Clipping paths
from CSS Masking
([CSS-MASKING], section 8).
Masking uses the luminance of the color channels and alpha channel in a referenced SVG element to define a supplemental set of alpha values which are multiplied to the alpha values already present in the graphics to which the mask is applied. The resulting alpha value is used as input to the Compositing and Blending operations described in the Compositing and Blending Specification [COMPOSITING-BLENDING]. Masking is described in detail in CSS Masking [CSS-MASKING].
A supplemental masking operation may also be specified by
applying a "global" opacity to a set of rendering operations.
In this case the mask is infinite, with a color of white and an
alpha channel of the given opacity value. (See the ‘opacity
’
property.)
SVG document fragments can be semi-opaque. In many environments (e.g., Web browsers), the SVG document fragment has a final compositing step where the document as a whole is blended translucently into the background canvas.
The EBNF grammar is as used in the XML specification, with the addition of ~, a case-insensitive literal: characters in the ASCII range (only) are declared to be case-insensitive. For example, ~"Hello" will match (H|h)(e|E)(l|L)(l|L)(o|O). This makes the productions much easier to read.
? | optional, zero or one |
+ | one or more |
* | zero or more |
| | alternation |
"string" | literal |
~"string" | case-insensitive literal |
[] | a character range |
[^] | excluded character range |
() | grouping |
We should reference css3-values, and not redefine a bunch of types in this chapter.
This section defines a number of common data types used in the definitions of SVG properties and attributes. Some data types that are not referenced by multiple properties and attributes are defined inline in subsequent chapters.
Note that, as mentioned below, the specification of some types is different for CSS property values in style sheets (in the ‘style’ attribute, ‘style’ element or an external style sheet) than it is for for XML attribute values (including presentation attributes). This is due to restrictions in the CSS grammar. For example, scientific notation is allowed in attributes, including presentation attributes, but not in style sheets.
The basic type <anything> is a sequence of zero or more characters. Specifically:
anything ::= Char*
where Char is the production for a character, as defined in XML 1.0 ([XML10], section 2.2).
A comma-separated list of compound selectors. When used, the scope in which the selectors are evaluated is also defined. Typically only the first matching element in tree order (as defined in [DOM4]) as a result of evaluating the list of selectors is used.
child-selector ::= select(compound selector#)
The basic type <color> is a CSS 2.1 compatible specification for a
color in the sRGB color space [SRGB].
<color> applies to SVG's use of the ‘color
’ property and
is a component of the definitions of properties ‘fill
’,
‘stroke
’, ‘stop-color
’, ‘flood-color
’ and
‘lighting-color
’, which also offer optional ICC-based color
specifications.
SVG supports all of the syntax alternatives for <color> defined in CSS 2.1 syntax and basic data types ([CSS21], section 4.3.6), with the exception that SVG allows an expanded list of recognized color keywords names.
A <color> is either a keyword (see Recognized color keyword names) or a numerical RGB specification.
In addition to these color keywords, users may specify keywords that correspond to the colors used by objects in the user's environment. The normative definition of these keywords is found in System Colors ([CSS21], section 18.2).
The format of an RGB value in hexadecimal notation is a "#" immediately followed by either three or six hexadecimal characters. The three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits, not by adding zeros. For example, #fb0 expands to #ffbb00. This ensures that white (#ffffff) can be specified with the short notation (#fff) and removes any dependencies on the color depth of the display.
The format of an RGB value in the functional notation is an RGB start-function followed by a comma-separated list of three numerical values (either three integer values or three percentage values) followed by ")". An RGB start-function is the case-insensitive string "rgb(", for example "RGB(" or "rGb(". For compatibility, the all-lowercase form "rgb(" is preferred.
The integer value 255 corresponds to 100%, and to F or FF in the hexadecimal notation: rgb(255,255,255) = rgb(100%,100%,100%) = #FFF. White space characters are allowed around the numerical values. All RGB colors are specified in the sRGB color space [SRGB]. Using sRGB provides an unambiguous and objectively measurable definition of the color, which can be related to international standards (see [COLORIMETRY]).
color ::= "#" hexdigit hexdigit hexdigit (hexdigit hexdigit hexdigit)? | "rgb(" wsp* integer comma integer comma integer wsp* ")" | "rgb(" wsp* integer "%" comma integer "%" comma integer "%" wsp* ")" | color-keyword hexdigit ::= [0-9A-Fa-f] comma ::= wsp* "," wsp*
where color-keyword matches (case insensitively) one of the color keywords listed in Recognized color keyword names below, or one of the system color keywords listed in System Colors ([CSS21], section 18.2).
The corresponding SVG DOM interface definitions for <color> are defined in Document Object Model CSS; in particular, see RGBColor ([DOM2STYLE], section 2.2).
Frequency values are used with aural properties. As defined in CSS 2.1, a frequency value is a <number> immediately followed by a frequency unit identifier. The frequency unit identifiers are:
Frequency values may not be negative.
In the SVG DOM, <frequency> values are represented using the CSSPrimitiveValue interface defined in Document Object Model CSS ([DOM2STYLE], section 2.2).
A gradient as defined by CSS Level 3 Image
Values [CSS3IMAGES] and can be used
as paint server for the properties ‘fill
’ and ‘stroke
’. Percentage values get resolved
against the bounding box of the element to which the gradient is applied.
An <icccolor> is an ICC color specification. In SVG 1.1, an ICC color specification is given by a name, which references a ‘color-profile’ element, and one or more color component values. The grammar is as follows:
icccolor ::= "icc-color(" author-ident (comma-wsp number)+ ")"
An image source (including gradients) as defined by CSS Level 4 Image Values ([CSS4IMAGES], section 4.3).
An <integer> is specified as an optional sign character ("+" or "-") followed by one or more digits "0" to "9":
integer ::= [+-]? [0-9]+
If the sign character is not present, the number is non-negative.
Unless stated otherwise for a particular attribute or property, the range for an <integer> encompasses (at a minimum) -2147483648 to 2147483647.
Within the SVG DOM, an <integer> is represented as a long or an SVGAnimatedInteger.
An Internationalized Resource Identifier (see IRI). For the specification of IRI references in SVG, see IRI references.
A length is a distance measurement, given as a number along with a unit which may be optional. Lengths are specified in one of two ways depending upon whether they are used in CSS property syntax or SVG presentation attribute syntax:
When a <length> is used in a style sheet or with a property in a ‘style’ attribute, the syntax must match the following pattern:
length ::= number (~"em" | ~"ex" | ~"px" | ~"in" | ~"cm" | ~"mm" | ~"pt" | ~"pc")?
See the CSS 2.1 specification for the meanings of the unit identifiers. The unit identifier may be in lower (recommended) or upper case.
For properties defined in CSS 2.1 [CSS21], a length unit identifier must be provided (for non-zero values). For SVG-specific properties, the length unit identifier is optional. If a unit is not provided, the length value represents a distance in the current user coordinate system.
When a <length> is used in an SVG presentation attribute, the syntax must match the following pattern:
length ::= number ("em" | "ex" | "px" | "in" | "cm" | "mm" | "pt" | "pc" | "%")?
The unit identifier, if present, must be in lower case; if not present, the length value represents a distance in the current user coordinate system.
Note that the non-property <length> definition also allows a percentage unit identifier. The meaning of a percentage length value depends on the attribute for which the percentage length value has been specified. Two common cases are: (a) when a percentage length value represents a percentage of the viewport width or height (refer to the section that discusses units in general), and (b) when a percentage length value represents a percentage of the bounding box width or height on a given object (refer to the section that describes object bounding box units).
In the SVG DOM, <length> values are represented using SVGLength or SVGAnimatedLength objects.
We should disentangle lengths and percentages.
A <list-of-strings> consists of a separated sequence of <string>s. String lists are white space-separated, where white space is defined as one or more of the following consecutive characters: "space" (U+0020), "tab" (U+0009), "line feed" (U+000A) and "carriage return" (U+000D).
The following is an EBNF grammar describing the <list-of-strings> syntax:
list-of-strings ::= string | string wsp list-of-strings string ::= [^#x9#xA#xD#x20]* wsp ::= [#x9#xA#xD#x20]+
(Where T is a type other than <string> and <family-name>.) A list consists of a separated sequence of values. Unless explicitly described differently, lists within SVG's XML attributes can be either comma-separated, with optional white space before or after the comma, or white space-separated.
White space in lists is defined as one or more of the following consecutive characters: "space" (U+0020), "tab" (U+0009), "line feed" (U+000A), "carriage return" (U+000D) and "form-feed" (U+000C).
The following is a template for an EBNF grammar describing the <list-of-Ts> syntax:
list-of-Ts ::= T | T comma-wsp list-of-Ts comma-wsp ::= (wsp+ ","? wsp*) | ("," wsp*) wsp ::= (#x20 | #x9 | #xD | #xA)
Within the SVG DOM, values of a <list-of-Ts> type are represented by an interface specific for the particular type T. For example, a <list-of-lengths> is represented in the SVG DOM using an SVGLengthList or SVGAnimatedLengthList object.
Real numbers are specified in one of two ways. When used in a style sheet, a <number> is defined as follows:
number ::= integer | [+-]? [0-9]* "." [0-9]+
This syntax is the same as the definition in CSS ([CSS21], section 4.3.1).
When used in an SVG attribute, a <number> is defined differently, to allow numbers with large magnitudes to be specified more concisely:
number ::= integer ([Ee] integer)? | [+-]? [0-9]* "." [0-9]+ ([Ee] integer)?
Within the SVG DOM, a <number> is represented as a float, SVGNumber or a SVGAnimatedNumber.
A pair of <number>s, where the second <number> is optional.
number-optional-number ::= number | number comma-wsp number
In the SVG DOM, a <number-optional-number> is represented using a pair of SVGAnimatedInteger or SVGAnimatedNumber objects.
The values for properties ‘fill
’ and ‘stroke
’
are specifications of the type of paint to use when filling or stroking
a given graphics element. The available options and syntax for
<paint> are described in
Specifying paint.
Percentages are specified as a number followed by a "%" character:
percentage ::= number "%"
Note that the definition of <number> depends on whether the percentage is specified in a style sheet or in an attribute that is not also a presentation attribute.
Percentage values are always relative to another value, for example a length. Each attribute or property that allows percentages also defines the reference distance measurement to which the percentage refers.
Within the SVG DOM, a <percentage> is represented using an SVGNumber or SVGAnimatedNumber object.
A time value is a <number> immediately followed by a time unit identifier. The time unit identifiers are:
In the SVG DOM, <time> values are represented using the CSSPrimitiveValue interface defined in Document Object Model CSS ([DOM2STYLE], section 2.2).
A <transform-list> is used to specify a list of coordinate system transformations. A detailed description of the possible values for a <transform-list> is given in Modifying the User Coordinate System: the transform property.
Within the SVG DOM, a <transform-list> value is represented using an SVGTransformList or SVGAnimatedTransformList object.
An XML name, as defined by the Name production in Extensible Markup Language (XML) 1.0 ([XML10], section 2.3).
Unless stated otherwise for a particular attribute or property, a <number> has the capacity for at least a single-precision floating point number and has a range (at a minimum) of -3.4e+38F to +3.4e+38F.
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 High-Quality SVG Viewers are required to use at least double-precision floating point for intermediate calculations on certain numerical operations.
The following is the list of recognized color keywords that can be used as a keyword value for data type <color>:
|
|
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) |
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.
SVGElement needs to gain IDL attributes for all of the event listener attributes that are supported. HTML conveniently has some interfaces we can use directly for that.
interface SVGElement : Element { attribute DOMString id; attribute DOMString xmlbase; readonly attribute SVGAnimatedString className; readonly attribute CSSStyleDeclaration style; attribute DOMString xmllang; attribute DOMString xmlspace; readonly attribute SVGSVGElement? ownerSVGElement; readonly attribute SVGElement? viewportElement; };
Used for attributes of type boolean which can be animated.
interface SVGAnimatedBoolean { attribute boolean baseVal; readonly attribute boolean animVal; };
Used for attributes of type DOMString which can be animated.
interface SVGAnimatedString { attribute DOMString baseVal; readonly attribute DOMString animVal; };
This interface defines a list of DOMString values.
SVGStringList has the same attributes and methods as other SVGxxxList interfaces. Implementers may consider using a single base class to implement the various SVGxxxList interfaces.
The supported property indices of an SVGStringList object is all non-negative integers less than the length of the list.
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); };
Used for attributes whose value must be a constant from a particular enumeration and which can be animated.
interface SVGAnimatedEnumeration { attribute unsigned short baseVal; readonly attribute unsigned short animVal; };
Used for attributes of basic type <integer> which can be animated.
interface SVGAnimatedInteger { attribute long baseVal; readonly attribute long animVal; };
Used for attributes of basic type <number>.
[Constructor, Constructor(float value)] interface SVGNumber { attribute float value; };
Used for attributes of basic type <number> which can be animated.
interface SVGAnimatedNumber { attribute float baseVal; readonly attribute float animVal; };
This interface defines a list of SVGNumber objects.
SVGNumberList has the same attributes and methods as other SVGxxxList interfaces. Implementers may consider using a single base class to implement the various SVGxxxList interfaces.
The supported property indices of an SVGNumberList object is all non-negative integers less than the length of the list.
An SVGNumberList 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.
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); };
Used for attributes which take a list of numbers and which can be animated.
interface SVGAnimatedNumberList { readonly attribute SVGNumberList baseVal; readonly attribute SVGNumberList animVal; };
The SVGLength interface corresponds to the <length> and <percentage> basic data types, and represents a length or percentage that consists of a numerical factor and a unit, where the unit is one of the set of units described in Units (em, ex, px, pt, pc, cm, mm and in), a percentage, a unitless number (user units), or "unknown".
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.
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. Unless otherwise described, an SVGLength object is not associated with any element and has unspecified directionality.
We need to define the behavior of converting values from/to percentages when the viewport width/height/size is zero.
[Constructor, Constructor(float value, optional unsigned short unitType), Constructor(DOMString 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 length value as a string. On getting, returns a string as follows:
On setting, updates the numeric factor and units type of the SVGLength object according to the result of parsing the assigned string as a <length> or <percentage>.
Sets the unit type of the length value to the type specified by unitType and sets the numeric factor value such that it represents the same absolute length. For example, if the original value were "0.5cm" and the method was invoked to convert to millimeters, then unitType would return SVG_LENGTHTYPE_MM and valueInSpecifiedUnits would return the numeric value 5.
If the old or new unit type is percentage and the SVGLength object has no associated element, then the percentages are considered to resolve against a length of 100 user units. For example, converting an SVGLength whose value is 20px to a percentage will result in the value being 20%.
SVG 2 Requirement: | Make it easier to read and write to attributes in the SVG DOM. |
---|---|
Resolution: | We will make it easier to read and write to attributes in the SVG DOM in SVG2. |
Purpose: | To avoid the awkward access to the base values of SVGAnimatedLengths. |
Owner: | Cameron (ACTION-3414) |
Used for attributes of basic type <length> which can be animated.
interface SVGAnimatedLength { readonly attribute SVGLength baseVal; readonly attribute SVGLength animVal; attribute float cm; attribute float em; attribute float ex; attribute float in; attribute float mm; attribute float pc; attribute float pt; attribute float px; };
We should add accessors for the ch
,
rem
, vw
, vh
, vmin
and vmax
units once we support css3-values more fully.
Since SVGAnimatedLength objects can represent percentage values too, what should we name the accessor for that unit?
Should we add a string accessor, perhaps named
asString
or value
, to avoid having to write for example
rect.x.baseVal.valueAsString
?
This interface defines a list of SVGLength objects.
SVGLengthList has the same attributes and methods as other SVGxxxList interfaces. Implementers may consider using a single base class to implement the various SVGxxxList interfaces.
The supported property indices of an SVGLengthList object is all non-negative integers less than the length of the list.
An SVGLengthList 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.
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); };
Used for attributes of type SVGLengthList which can be animated.
interface SVGAnimatedLengthList { readonly attribute SVGLengthList baseVal; readonly attribute SVGLengthList animVal; attribute float cm; attribute float em; attribute float ex; attribute float in; attribute float mm; attribute float pc; attribute float pt; attribute float px; };
If any changes to the unit accessors are made to SVGAnimatedLength they should be made here too.
The SVGAngle interface corresponds to the <angle> basic data type, and represents an angle that consists of a numerical factor and a unit, where the unit is degrees, radians, grads, unitless numbers or "unknown".
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.
[Constructor, Constructor(float value, optional unsigned short unitType), Constructor(DOMString 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 angle value as a string. On getting, returns a string as follows:
On setting, updates the numeric factor and units type of the SVGAngle object according to the result of parsing the assigned string as an <angle>.
Sets the unit type of the angle value to the type specified by unitType and sets the numeric factor value such that it represents the same absolute angle. For example, if the original value were "180deg" and the method was invoked to convert to radians, then unitType would return SVG_ANGLETYPE_RAD and valueInSpecifiedUnits would return the numeric value π.
Used for attributes of basic data type <angle> that can be animated.
interface SVGAnimatedAngle { readonly attribute SVGAngle baseVal; readonly attribute SVGAngle animVal; };
Represents rectangular geometry. Rectangles are defined as consisting of a (x,y) coordinate pair identifying a minimum X value, a minimum Y value, and a width and height, which are usually constrained to be non-negative.
An SVGRect 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.
[Constructor, Constructor(float x, float y, float width, float height)] interface SVGRect { attribute float x; attribute float y; attribute float width; attribute float height; };
Used for attributes of type SVGRect which can be animated.
interface SVGAnimatedRect { readonly attribute SVGRect baseVal; readonly attribute SVGRect animVal; };
The SVGUnitTypes interface defines a commonly used set of constants and is a base interface used by SVGGradientElement, SVGPatternElement, SVGClipPathElement, SVGMaskElement and SVGFilterElement.
[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; };
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) |
Interface SVGGraphicsElement represents SVG elements whose primary purpose
is to directly render graphics into a group. The
‘transform
’ property applies to all SVGGraphicsElement. All SVGGraphicsElement
have a bounding box in current user space.
interface SVGGraphicsElement : SVGElement { readonly attribute SVGAnimatedTransformList transform; readonly attribute SVGElement? nearestViewportElement; readonly attribute SVGElement? farthestViewportElement; SVGRect getBBox(); SVGRect getStrokeBBox(); SVGMatrix? getCTM(); SVGMatrix? getScreenCTM(); SVGMatrix getTransformToElement(SVGGraphicsElement element); }; SVGGraphicsElement implements SVGTests;
transform
’ on the given element.
This needs to be updated to reflect the value of the ‘transform
’
property.
transform
’ property) on the
geometry of all contained graphics elements, exclusive of stroking, clipping, masking and
filter effects. Note that getBBox must return the actual bounding box
at the time the method was called, even in case the element has not
yet been rendered.
transform
’ property) on the
geometry of all contained graphics elements, exclusive of clipping, masking and
filter effects. The stroke bounding box takes the stroke style
properties ‘stroke-width
’, ‘stroke-linecap
’, ‘stroke-linejoin
’,
‘stroke-miterlimit
’, ‘stroke-dasharray
’ and ‘stroke-dashoffset
’
into account. Note that getStrokeBBox must
return the actual union of the bounding box at the time the method was called,
even in case the element has not yet been rendered.
transform
’ property) to the viewport
coordinate system for the nearestViewportElement. Note that null
is returned if this element is not hooked into the document tree.
transform
’ property) to the parent
user agent's notice of a "pixel". For display devices, ideally this
represents a physical screen pixel. For other devices or environments
where physical pixel sizes are not known, then an algorithm similar to
the CSS 2.1 definition of a "pixel" can be used instead. Note that null
is returned if this element is not hooked into the document tree. This
method would have been more aptly named as getClientCTM
,
but the name getScreenCTM
is kept for historical reasons.
transform
’ property)
to the user coordinate system on parameter element
(after application of its ‘transform
’ property).
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 { bool isPointInFill(SVGPoint point); bool isPointInStroke(SVGPoint point); };
pointer-events
’
property on the element determines whether a point is considered to be
within the fill.
pointer-events
’
property on the element determines whether a point is considered to be
within the stroke.
Interface SVGTests defines an interface which applies to all elements which have attributes ‘requiredFeatures’, ‘requiredExtensions’ and ‘systemLanguage’.
[NoInterfaceObject] interface SVGTests { readonly attribute SVGStringList requiredFeatures; readonly attribute SVGStringList requiredExtensions; readonly attribute SVGStringList systemLanguage; boolean hasExtension(DOMString extension); };
Interface SVGFitToViewBox defines DOM attributes that apply to elements which have XML attributes ‘viewBox’ and ‘preserveAspectRatio’.
[NoInterfaceObject] interface SVGFitToViewBox { readonly attribute SVGAnimatedRect viewBox; readonly attribute SVGAnimatedPreserveAspectRatio preserveAspectRatio; };
The SVGZoomAndPan interface defines attribute zoomAndPan and associated constants.
[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; };
interface SVGViewSpec { readonly attribute SVGTransformList transform; readonly attribute SVGElement viewTarget; readonly attribute DOMString viewBoxString; readonly attribute DOMString preserveAspectRatioString; readonly attribute DOMString transformString; readonly attribute DOMString viewTargetString; }; SVGViewSpec implements SVGFitToViewBox; SVGViewSpec implements SVGZoomAndPan;
Interface SVGURIReference defines an interface which applies to all elements which have an ‘xlink:href’ attribute.
[NoInterfaceObject] interface SVGURIReference { readonly attribute SVGAnimatedString href; };
SVG extends interface CSSRule with interface SVGCSSRule by adding an SVGColorProfileRule rule to allow for specification of ICC-based color.
It is likely that this extension will become part of a future version of CSS and DOM.
interface SVGCSSRule : CSSRule { const unsigned short COLOR_PROFILE_RULE = 7; };
The SVGRenderingIntent interface defines the enumerated list of possible values for ‘rendering-intent’ attributes or descriptors.
[NoInterfaceObject] interface SVGRenderingIntent { // Rendering Intent Types const unsigned short RENDERING_INTENT_UNKNOWN = 0; const unsigned short RENDERING_INTENT_AUTO = 1; const unsigned short RENDERING_INTENT_PERCEPTUAL = 2; const unsigned short RENDERING_INTENT_RELATIVE_COLORIMETRIC = 3; const unsigned short RENDERING_INTENT_SATURATION = 4; const unsigned short RENDERING_INTENT_ABSOLUTE_COLORIMETRIC = 5; };
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 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" version="1.1"> <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 canvas 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 viewport. (See Establishing a new viewport.)
In all cases, 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. The following are possible ways to provide a namespace declaration. 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" …> <rect …/> </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" …> <svg:rect …/> </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].
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.
SVG 2 Requirement: | Should support the playbackOrder attribute to inform UA to not display controls to seek backwards. |
---|---|
Resolution: | Support the playbackOrder attribute. |
Purpose: | To inform UA to not display controls to seek backwards. |
Owner: | Cyril |
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) |
SVG 2 Requirement: | Support a means for having SMIL animations start before their time container has fully loaded. |
---|---|
Resolution: | Timeline control. |
Purpose: | To start animations before the SVG document is fully loaded (useful for large SVG documents). |
Owner: | Cyril |
Attribute definitions:
Name | Value | Lacuna value | Animatable |
---|---|---|---|
version | <number> | (none) | no |
Indicates the SVG language version to which this document fragment conforms.
In SVG 1.0 [SVG10], this attribute was fixed to the value '1.0'. For SVG 1.1, the attribute should have the value '1.1'.
What are we doing with the ‘version’ attribute? It's not clear whether it is useful to keep.
Name | Value | Lacuna value | Animatable |
---|---|---|---|
baseProfile | <anything> | none | no |
Describes the minimum SVG language profile that the author believes is necessary to correctly render the content. The attribute does not specify any processing restrictions; It can be considered metadata. For example, the value of the attribute could be used by an authoring tool to warn the user when they are modifying the document beyond the scope of the specified base profile. Each SVG profile should define the text that is appropriate for this attribute.
It's unlikely SVG 2 will have profiles as 1.0 and 1.1 did. Do we keep the attribute in case others wish to profile SVG? (Or should we be discouraging that?)
Name | Value | Lacuna value | Animatable |
---|---|---|---|
x, y | <length> | 0 | yes |
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.
Name | Value | Lacuna value | Animatable |
---|---|---|---|
width, height | <length> | <percentage> | 100% | yes |
For outermost svg elements, the ‘width’ and ‘height’ attributes specify the intrinsice 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.
A negative value is an error (see Error processing). A value of zero disables rendering of the element.
When zero is used on an outer ‘svg’ element, does this disable rendering too? Or does it just affect the intrinsic size?
Name | Value | Lacuna value | Animatable |
---|---|---|---|
preserveAspectRatio | defer? <align> [ meet | slice ]? | xMidYMid meet | yes |
Specifies the fitting behavior when the aspect ratio of the ‘svg’ element does not match the aspect ratio of the rectangle it is placed in. See the definition of ‘preserveAspectRatio’ for details.
Name | Value | Lacuna 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.
Name | Value | Lacuna value | Animatable |
---|---|---|---|
playbackOrder | forwardOnly | all | all | no |
This attribute may be harmonized and/or replaced with the work done as part of the Web Animation specification.
Indicates whether it is possible to seek backwards in the document. In earlier versions of SVG there was no need to put restrictions on the direction of seeking but with the newly introduced facilities for long-running documents (e.g. the ‘discard’ element) there is sometimes a need to restrict this.
If ‘playbackOrder’ is set to 'forwardOnly', the content will probably contain ‘discard’ elements or scripts that destroy resources, thus seeking back in the document's timeline may result in missing content. If ‘playbackOrder’ is 'forwardOnly', the content should not provide a way, through hyperlinking or script, of seeking backwards in the timeline. Similarly the UA should disable any controls it may provide in the user interface for seeking backwards. Content with playbackOrder="forwardOnly" that provides a mechanism for seeking backwards in time may result in undefined behavior or a document that is in error.
Can't we define this so that there is no undefined behavior?
Attribute values have the following meanings:
Name | Value | Lacuna value | Animatable |
---|---|---|---|
timelineBegin | onLoad | onStart | onLoad | no |
This attribute may be harmonized and/or replaced with the work done as part of the Web Animation specification.
Controls the initialization of the timeline for the document.
The ‘svg’ element controls the document timeline, which is the timeline of the ‘svg’ element's time container. For progressively loaded animations, the author would typically set this attribute to 'onStart', thus allowing the timeline to begin as the document loads, rather than waiting until the complete document is loaded.
Attribute values have the following meanings:
load
event for the
rootmost ‘svg’ element is triggered.
What about when the SVG document fragment is within
an XHTML document? Is there a single timeline for the whole document, and if so,
does it start at the parse time for the first <svg>
start tag?
What about when using the HTML parser?
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 viewport.
This paragraph feels out of place just after the list of attributes specific to ‘svg’.
The ‘g’ element is a container element for grouping together related graphics elements.
Grouping constructs, when used in conjunction with the ‘desc’ and ‘title’ elements, provide information about document structure and semantics. Documents that are rich in structure may be rendered graphically, as speech, or as braille, and thus promote accessibility.
That generously structured content with ‘title’ and ‘desc’ is more accessible isn't necessarily true. It also seems like a stretch to claim that documents "rich in structure" can be rendered as speech or braille, without specific references to how that can be achieved. More fundamental uses of grouping that should be mentioned are (a) for specifying common styling of inherited properties, and (b) for selecting elements to apply a group effect like filters and group opacity.
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 canvas using 'rect' element --> <rect x=".01cm" y=".01cm" width="4.98cm" height="4.98cm" fill="none" stroke="blue" stroke-width=".02cm"/> </svg>
A ‘g’ element can contain other ‘g’ elements nested within it, to an arbitrary depth. Thus, the following is possible:
<?xml version="1.0" standalone="no"?> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="4in" height="3in"> <desc>Groups can nest</desc> <g> <g> <g> </g> </g> </g> </svg>
This is not a particularly useful example.
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) |
Any element that is not contained within a ‘g’ is treated (at least conceptually) as if it were in its own group.
It is unclear what this sentence actually means. Does it mean that all operations that apply to groups (such as group opacity, filter effects, etc.) can apply to single elements too? If so, then it should say that.
SVG allows graphical objects to be defined for later reuse. To do this, it makes extensive use of IRI 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: ‘altGlyphDef’, ‘clipPath’, ‘cursor’, ‘filter’, ‘linearGradient’, ‘marker’, ‘mask’, ‘pattern’, ‘radialGradient’ and ‘symbol’. Defining these elements inside of a ‘defs’ element promotes understandability of the SVG content and thus promotes accessibility.
Again this claim about accessibility is dubious.
We should have a term for definition elements (since we now have a corresponding IDL interface) and reference it here.
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.
To provide some SVG user agents with an opportunity to implement efficient implementations in streaming environments, creators of SVG content are encouraged to place all elements which are targets of local IRI references within a ‘defs’ element which is a direct child of one of the ancestors of the referencing element. For example:
Is this really about efficiency of implementations? If anything, it looks like it is ensuring progressively rendered documents don't make forward references that would otherwise cause an incorrect rendering before the referenced element is loaded.
<?xml version="1.0" standalone="no"?> <svg width="8cm" height="3cm" xmlns="http://www.w3.org/2000/svg" version="1.1"> <desc>Local URI references within ancestor's 'defs' element.</desc> <defs> <linearGradient id="Gradient01"> <stop offset="20%" stop-color="#39F" /> <stop offset="90%" stop-color="#F3F" /> </linearGradient> </defs> <rect x="1cm" y="1cm" width="6cm" height="1cm" fill="url(#Gradient01)" /> <!-- Show outline of canvas using 'rect' element --> <rect x=".01cm" y=".01cm" width="7.98cm" height="2.98cm" fill="none" stroke="blue" stroke-width=".02cm" /> </svg>
In the document above, the linear gradient is defined within a ‘defs’ element which is the direct child of the ‘svg’ element, which in turn is an ancestor of the ‘rect’ element which references the linear gradient. Thus, the above document conforms to the guideline.
Would this element be better as part of the Animation chapter? It also needs to be a member of the element categories that other animation elements are, and an IDL interface needs to be written for it.
SVG 2 Requirement: | Have the ‘discard’ element to declaratively discard elements from the document tree. |
---|---|
Resolution: | SVG 2 will support the discard element. |
Purpose: | To conserve memory while displaying long-running documents. |
Owner: | Cyril (ACTION-3319) |
Need to define SVGDiscardElement DOM interface for ‘discard’ element.
The ‘discard’ element allows authors to specify the time at which particular elements are to be discarded, thereby reducing the resources required by an SVG user agent. This is particularly useful to help SVG viewers conserve memory while displaying long-running documents. This element will not be processed by static SVG viewers.
The ‘discard’ element may occur wherever the ‘animate’ element may.
Attribute definitions:
Name | Value | Lacuna value | Animatable |
---|---|---|---|
href | <iri> | (none) | no |
An IRI reference that identifies the target element to discard. See the definition of ‘href’ on animation elements for details on identifying a target element.
Note that if the target element is not part of the current SVG document fragment then whether the target element will be removed or not is defined by the host language.
If the ‘href’ attribute is not provided, then the target element will be the immediate parent element of the discard element.
Name | Value | Lacuna value | Animatable |
---|---|---|---|
begin | <begin-value-list> | 0s | no |
Indicates when the target element will be discarded. See the definition of ‘begin’ on animation elements for details.
The ‘discard’
element has an implicit
simple duration
of "indefinite". As soon as the element's
active duration
starts, the SVG user agent
discards the element identified by the
‘href’
attribute ([SMIL], section 5.4.5).
The removal operation acts as if
removeChild
were called on the parent of the target element with the target element as
parameter. [DOM4] The SVG user agent
must remove the target node as well as all of its attributes and descendants.
After removal of the target element, the ‘discard’ element is no longer useful. It must also be discarded following the target element removal. If the ‘href’ attribute has an invalid IRI reference (the target element did not exist, for example), the ‘discard’ element itself must still be removed following activation.
Seeking backwards in the timeline ([SMIL], section 5.4.5) must not re-insert the discarded elements. Discarded elements are intended to be completely removed from memory. So, authors are encouraged to set the ‘playbackOrder’ attribute to "forwardOnly" when using the ‘discard’ element.
The ‘discard’ element itself can be discarded prior to its activation, in which case it will never trigger the removal of its own target element. SVG user agents must allow the ‘discard’ element to be the target of another ‘discard’ element.
The following example demonstrates a simple usage of the ‘discard’ element. The list below describes relevant behavior in the document timeline of this example:
<svg xmlns="http://www.w3.org/2000/svg" width="352" height="240" playbackOrder="forwardOnly"> <ellipse cx="98.5" cy="17.5" rx="20.5" ry="17.5" fill="blue" stroke="black" transform="translate(9 252) translate(3 -296)"> <animateTransform attributeName="transform" begin="0s" dur="2s" fill="remove" calcMode="linear" type="translate" additive="sum" from="0 0" to="-18 305"/> <discard begin="2s"/> </ellipse> <rect x="182" y="-39" width="39" height="30" fill="red" stroke="black" transform="translate(30 301)"> <animateTransform attributeName="transform" begin="1s" dur="2s" fill="remove" calcMode="linear" type="translate" additive="sum" from="0 0" to="-26 -304"/> <discard begin="3s"/> </rect> <polygon points="-66,83.5814 -43,123.419 -89,123.419" fill="green" stroke="black" transform="matrix(1 0 0 1.1798 0 -18.6096)"> <animateTransform attributeName="transform" begin="2s" dur="2s" fill="remove" calcMode="linear" type="translate" additive="sum" from="0 0" to="460 63.5699"/> <discard begin="4s"/> </polygon> </svg>
The attribute ‘lang’ added to allow internationalization of the ‘desc’ and ‘title’ elements.
Adding 'lang' resolved at Rigi Kaltbad face-to-face. Removed text that limited number of 'desc' and 'title' elements.
Is there any updated wording from SVG Tiny 1.2 that we should be using wrt tooltips?
Each container element or graphics element in an SVG drawing can supply one or more ‘desc’ and/or one or more ‘title’ description strings where the description is text-only. When the current SVG document fragment is rendered as SVG on visual media, ‘desc’ and ‘title’ elements are not rendered as part of the graphics. User agents may, however, for example, display the ‘title’ element as a tooltip, as the pointing device moves over particular elements. 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. This is readily achieved by using a different (perhaps user) style sheet. 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.
I don't think it is easy to use a style sheet to cause an element's ‘title’ to be rendered in place of its graphics.
More than one ‘desc’ or ‘title’ may be present with different ‘lang’ attributes. The text displayed will be the text from the element where the ‘lang’ attribute best matches the language set by the user agent. If no match exists, the text from the first element is used (to allow default text to be given for legacy renderers). If multiple equally valid matches exist, the first match is used.
'lang' should be defined here (rather than pointing to the glyph definition).
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" version="1.1" width="4in" height="3in"> <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> <!-- Bar chart defined as vector data --> </g> </svg>
Description and title elements can contain marked-up text from other namespaces. Here is an example:
<?xml version="1.0" standalone="yes"?> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="4in" height="3in"> <desc xmlns:mydoc="http://example.org/mydoc"> <mydoc:title>This is an example SVG file</mydoc:title> <mydoc:para>The global description uses markup from the <mydoc:emph>mydoc</mydoc:emph> namespace.</mydoc:para> </desc> <g> <!-- the picture goes here --> </g> </svg>
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.
Authors should always provide a ‘title’ child element to the outermost svg element within a stand-alone SVG document. The ‘title’ child element to an ‘svg’ element serves the purposes of identifying the content of the given SVG document fragment. 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. The mechanism for doing so depends on the user agent (e.g., as a caption, spoken).
We have this sentence here about tooltips which is stronger than the earlier note that some implementations do this. We should look at how HTML describes the ‘title’ attribute and whether a tooltip is required, suggested, etc., and follow that.
Once we have said how ARIA attributes can be used in SVG, we might want to define ‘title’ and ‘desc’ in a manner consistent with them, so that it is clear what it means for example for an element to have both a ‘desc’ element child and an ‘aria-describedby’ attribute.
The ‘symbol’ element is used to define graphical template objects which can be instantiated by a ‘use’ element.
The use of ‘symbol’ elements for graphics that are used multiple times in the same document adds structure and semantics. Documents that are rich in structure may be rendered graphically, as speech, or as braille, and thus promote accessibility.
Again this mention of accessibility through the use of structure (this time with ‘symbol’ elements). We should include an example here or in the Accessibility appendix that shows how this is the case and what the actual effects of structuring content with ‘symbol’ are.
The key distinctions between a ‘symbol’ and a ‘g’ are:
Closely related to the ‘symbol’ element are the ‘marker’ and ‘pattern’ elements.
‘symbol’ elements are never 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.
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) |
Any ‘svg’, ‘symbol’, ‘g’, graphics element or other ‘use’ is potentially a template object that can be re-used (i.e., "instanced") in the SVG document via a ‘use’ element. The ‘use’ element references another element and indicates that the graphical contents of that element is included/drawn at that given point in the document.
‘use’ is described as referencing template objects, but the parameters of the template are limited – just different inherited property values.
The ‘use’ element can reference an entire SVG document by specifying an ‘xlink:href’ value without a fragment. Such references are taken to be referring to the root element of the referenced document.
This allows an entire SVG document to be referenced without having to ensure that it has an ID on its root element.
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.
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.
We should define the behavior of ‘use’ in terms of Web Components.
For user agents that support Styling with CSS, 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.
We should be requiring CSS styling in SVG 2. Also, hopefully, how styles can apply or not to elements in the shadow tree (and how event handling works, below) should be specified by how we define ‘use’ to work in terms of Web Components.
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.
If event attributes are assigned to referenced elements, then the actual target for the event will be the SVGElementInstance object within the "instance tree" corresponding to the given referenced element.
Once we define ‘use’ in terms of Web Components, will we drop instance trees?
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, except that events are dispatched to the SVGElementInstance objects. The event's target and currentTarget attributes are set to the SVGElementInstance 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.
An element and all its corresponding SVGElementInstance objects share an event listener list. The currentTarget attribute of the event can be used to determine through which object an event listener was invoked.
The behavior of the ‘visibility
’ property conforms to
this model of property inheritance. Thus, 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'.
Why is ‘visibility
’ called out specially? It might
be better just to include an example that shows this.
Animations on a referenced element will cause the instances to also be animated.
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.
If the ‘use’ element references a ‘symbol’ element:
In the generated content, the ‘use’ will be replaced by ‘g’, where all attributes
from the ‘use’ element
except for ‘x’, ‘y’, ‘width’, ‘height’ 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 referenced ‘symbol’ and its contents are
deep-cloned into the generated tree, with the exception that
the ‘symbol’ is replaced by an ‘svg’. This generated ‘svg’ will always have
explicit values for attributes ‘width’ and ‘height’. If attributes ‘width’ and/or ‘height’ are provided on the ‘use’ element, then these
attributes will be transferred to the generated ‘svg’. If attributes ‘width’ and/or ‘height’ are not specified, the
generated ‘svg’ element will use values
of '100%' for these attributes.
If the ‘use’ element references an ‘svg’ element:
In the generated content, the ‘use’ will be replaced by ‘g’, where all attributes
from the ‘use’ element
except for ‘x’, ‘y’, ‘width’, ‘height’ 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 referenced ‘svg’ and its contents are
deep-cloned into the generated tree. If attributes ‘width’ and/or ‘height’ are provided on the ‘use’ element, then these values
will override the corresponding attributes on the ‘svg’ in the generated
tree.
Otherwise:
In the generated content, the ‘use’ will be replaced by ‘g’, where all attributes
from the ‘use’ element
except for ‘x’, ‘y’, ‘width’, ‘height’ 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 referenced
object and its contents are deep-cloned into the generated
tree.
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" xmlns:xlink="http://www.w3.org/1999/xlink"> <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" xlink:href="#MyRect" /> </svg>
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>
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" xmlns:xlink="http://www.w3.org/1999/xlink"> <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" xlink:href="#MySymbol" /> </svg>
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>
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" xmlns:xlink="http://www.w3.org/1999/xlink"> <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 xlink:href="#MyRect" transform="translate(20,2.5) rotate(10)" /> </svg>
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>
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" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <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" xlink:href="#MyPath" class="MyUseClass" style="/* rule 12 */ stroke-dashoffset:50" /> </g> </svg>
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>
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.
Attribute definitions:
Name | Value | Lacuna value | Animatable |
---|---|---|---|
x, y | <length> | 0 | yes |
width, height | <length> | (see prose) | yes |
The ‘x’, ‘y’, ‘width’ and ‘height’ attributes specify the positioning of the referenced element. The ‘width’ and ‘height’ attributes have different lacuna values depending on the type of the referenced element:
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 | Lacuna value | Animatable |
---|---|---|---|
href | <iri> | (none) | yes |
An IRI reference to the element/fragment within an SVG document to be cloned for rendering.
The ‘image’ element indicates that the contents of a complete file are to be rendered into a given rectangle within the current user coordinate system. The ‘image’ element can refer to raster image files such as PNG or JPEG or to files with MIME type of "image/svg+xml". Conforming SVG viewers need to support at least PNG, JPEG and SVG format files.
The result of processing an ‘image’ is always a four-channel RGBA result. When an ‘image’ element references a raster image file such as PNG or JPEG files which only has three channels (RGB), then the effect is as if the object were converted into a 4-channel RGBA image with the alpha channel uniformly set to 1. For a single-channel raster image, the effect is as if the object were converted into a 4-channel RGBA image, where the single channel from the referenced object is used to compute the three color channels and the alpha channel is uniformly set to 1.
An ‘image’ element establishes a new viewport for the referenced file as described in Establishing a new viewport. The bounds for the new viewport are defined by attributes ‘x’, ‘y’, ‘width’ and ‘height’. The placement and scaling of the referenced image are controlled by the ‘preserveAspectRatio’ attribute on the ‘image’ element.
When an ‘image’ element
references an SVG image, the ‘clip
’ and ‘overflow
’ properties on the root element in
the referenced SVG image are ignored (in the same manner as the
‘x’, ‘y’, ‘width’ and ‘height’ attributes are ignored). Unless the value of
‘preserveAspectRatio’ on the ‘image’ element starts with 'defer',
the ‘preserveAspectRatio’ attribute on the root element in
the referenced SVG image is also ignored (see ‘preserveAspectRatio’
for details). Instead, the ‘preserveAspectRatio’ attribute on
the referencing ‘image’
element defines how the SVG image content is fitted into the
viewport and the ‘clip
’ and ‘overflow
’ properties on the ‘image’ element define how the SVG
image content is clipped (or not) relative to the viewport.
Why does it make sense to override ‘clip
’
but not ‘clip-path
’?
The value of the ‘viewBox’ attribute to use when evaluating the ‘preserveAspectRatio’ attribute is defined by the referenced content. For content that clearly identifies a viewBox (e.g. an SVG file with the ‘viewBox’ attribute on the outermost svg element) that value should be used. For most raster content (PNG, JPEG) the bounds of the image should be used (i.e. the ‘image’ element has an implicit ‘viewBox’ of '0 0 raster-image-width raster-image-height'). Where no value is readily available (e.g. an SVG file with no ‘viewBox’ attribute on the outermost svg element) the ‘preserveAspectRatio’ attribute is ignored, and only the translation due to the ‘x’ & ‘y’ attributes of the viewport is used to display the content.
We should say how the use of an #xywh
media fragment interacts with the the above.
For example, if the image element referenced a PNG or JPEG and preserveAspectRatio="xMinYMin meet", then the aspect ratio of the raster would be preserved (which means that the scale factor from image's coordinates to current user space coordinates would be the same for both X and Y), the raster would be sized as large as possible while ensuring that the entire raster fits within the viewport, and the top/left of the raster would be aligned with the top/left of the viewport as defined by the attributes ‘x’, ‘y’, ‘width’ and ‘height’ on the ‘image’ element. If the value of ‘preserveAspectRatio’ was 'none' then aspect ratio of the image would not be preserved. The image would be fitted such that the top/left corner of the raster exactly aligns with coordinate (‘x’, ‘y’) and the bottom/right corner of the raster exactly aligns with coordinate (‘x’+‘width’, ‘y’+‘height’).
The resource referenced by the ‘image’ element represents a separate document which generates its own parse tree and document object model (if the resource is XML). Thus, there is no inheritance of properties into the image.
Unlike ‘use’, the ‘image’ element cannot reference elements within an SVG file.
SVG 2 Requirement: | Support auto-sized images. |
---|---|
Resolution: | We will allow auto-sized images in SVG 2. |
Purpose: | To allow raster images to use their own size without the need to set width and height. |
Owner: | Cameron (ACTION-3340) |
SVG 2 Requirement: | Support selecting part of an ‘image’ for display. |
---|---|
Resolution: | We will have a method for ‘image’ to select a part of an image to display, maybe by allowing ‘viewBox’ on it. |
Purpose: | To allow selection of part of an image without requiring the author to manually slice the image. |
Owner: | Nobody |
SVG 2 Requirement: | Support the ‘object-fit’ and ‘object-position’ properties from css3-images. |
---|---|
Resolution: | SVG 2 will depend on CSS3 Image Values and CSS4 Image Values. |
Purpose: | To align with the CSS way of specifying image fitting that ‘preserveAspectRatio’ provides. |
Owner: | Cameron or Erik (no action) |
Attribute definitions:
Name | Value | Lacuna value | Animatable |
---|---|---|---|
x, y | <length> | 0 | yes |
width, height | <length> | auto | 0 | yes |
The ‘x’, ‘y’, ‘width’ and ‘height’ attributes specify the rectangular region into which the referenced image is placed.
A negative value for ‘width’ or ‘height’ is invalid (see Error processing). A value of zero for either attribute disables rendering of the element.
The 'auto' value for ‘width’ and ‘height’ is used to size the ‘image’ element automatically based on the intrinsic size or aspect ratio of the referenced image. If the intrinsic aspect ratio of the referenced image is unknown, it is assumed to be 2:1. If the intrinsic size of the referenced image is unknown, it is assumed to be 300×150, just as is required for CSS replaced elements. If 'auto' is specified for just one of ‘width’ or ‘height’, then the other is determined based on the intrinsic aspect ratio. The automatically determined ‘width’ and ‘height’ values are interpreted as user units, and are reflected in the x and y IDL attributes as SVG_LENGTHTYPE_NUMBER values.
Name | Value | Lacuna value | Animatable |
---|---|---|---|
xlink:href | <iri> | (none) | yes |
An IRI reference identifying the image to render.
Name | Value | Lacuna value | Animatable |
---|---|---|---|
preserveAspectRatio | defer? <align> [ meet | slice ]? | xMidYMid meet | yes |
Specifies the fitting behavior when the aspect ratio of the referenced image does not match the aspect ratio of the rectangle it is placed in. See the definition of ‘preserveAspectRatio’ for details.
An example:
<?xml version="1.0" standalone="no"?> <svg width="4in" height="3in" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <desc>This graphic links to an external image </desc> <image x="200" y="200" width="100px" height="100px" xlink:href="myimage.png"> <title>My image</title> </image> </svg>
SVG contains a ‘switch’ element along with attributes ‘requiredFeatures’, ‘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 ‘requiredFeatures’, ‘requiredExtensions’ and ‘systemLanguage’ act as tests and return either true or false results. 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.
It sounds strange to talk about attributes "returning" a value.
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:
The ‘switch’ element evaluates the ‘requiredFeatures’, ‘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.
For more information and an example, see Embedding foreign object types.
Name | Value | Lacuna value | Animatable |
---|---|---|---|
requiredFeatures | list-of-features | (none) | no |
Need a grammar for list-of-features.
The value is a list of feature strings, with the individual values separated by white space. Determines whether all of the named features are supported by the user agent. Only feature strings defined in the Feature String appendix are allowed. If all of the given features are supported, then the attribute evaluates to true; otherwise, the current element and its children are skipped and thus will not be rendered.
If the attribute is not present, then its implicit return value is "true". If a null string or empty string value is given to attribute ‘requiredFeatures’, the attribute returns "false".
‘requiredFeatures’ is often used in conjunction with the ‘switch’ element. If the ‘requiredFeatures’ is used in other situations, then it represents a simple switch on the given element whether to render the element or not.
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 IRI reference.
Name | Value | Lacuna value | Animatable |
---|---|---|---|
requiredExtensions | list-of-extensions | (none) | no |
The value is a list of IRI 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 IRI reference contains white space within itself, that white space must be escaped.
If the attribute is not present, then its implicit return value is "true". If a null string or empty string value is given to attribute ‘requiredExtensions’, the attribute returns "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 IRI 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.
The attribute value is a comma-separated list of language names 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.
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.
For the ‘systemLanguage’ attribute: Animatable: no.
If the attribute is not present, then its implicit return value is "true". If a null string or empty string value is given to attribute ‘systemLanguage’, the attribute returns "false".
‘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.
Should have an attribute definition table in this section.
The following list describes the applicability of the test attributes to the elements that do not directly produce rendering.
This was already mentioned in the "Conditional processing overview" section. We should just describe this once.
The ‘id’ and ‘xml:base’ attributes are available on all SVG elements:
Name | Value | Lacuna value | Animatable |
---|---|---|---|
id | name | (none) | no |
Need a grammar for name.
Standard XML attribute for assigning a unique name to an element. Refer to the Extensible Markup Language (XML) 1.0 Recommendation [XML10].
Name | Value | Lacuna value | Animatable |
---|---|---|---|
xml:base | <iri> | (none) | no |
Specifies a base IRI other than the base IRI of the document or external entity. Refer to the XML Base specification [XML-BASE].
Are we happy to keep promoting the use of ‘xml:base’? Is it a use case worth trying to include a more HTML-like syntax for – the ‘base’ element? We anyway need to define somewhere what effect the HTML ‘base’ element has on any SVG document fragments.
Elements that might contain character data content have attributes ‘xml:lang’ and ‘xml:space’.
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 and ACTION-3005, done) |
Should we be moving ‘lang’ instead of ‘xlink:lang’?
Name | Value | Lacuna value | Animatable |
---|---|---|---|
xml:lang | languageID | (none) | no |
Need a grammar for languageID.
Standard XML attribute to specify the language (e.g., English) used in the contents and attribute values of particular elements. Refer to the Extensible Markup Language (XML) 1.0 Recommendation [XML10].
Name | Value | Lacuna value | Animatable |
---|---|---|---|
xml:space | default | preserve | default | no |
Deprecated XML attribute to specify whether white space is preserved in character data. The only possible values are 'default' and 'preserve'. 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.
Rendered SVG elements 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).
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 | Lacuna value | Animatable |
---|---|---|---|
role | white-space space separated tokens having values defined in Definition of Roles ([ARIA], section 5.4) | default | no |
The role value is a set of white-space separated machine-extractable semantic information used to define the purpose of the element.
Every renderable SVG element 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 langauges 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. Unlike some other host languages, SVG is not considered to have strong native host language semantics in terms of the user interface, consequently state and property attributes are processed according to the ARIA and ARIA User Agent Implementation Guide specifications. [ARIA] [ARIAIMPL]
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 ‘href’ 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.
HTML defines title, referrer and domain. We should remove them and file a bug on HTML to ensure that title does the right thing for SVG documents.
For historical reasons, Window objects must also have a writable, configurable, non-enumerable property named SVGDocument whose value is the Document interface object.
partial interface Document { readonly attribute DOMString title; readonly attribute DOMString referrer; readonly attribute DOMString domain; readonly attribute SVGSVGElement rootElement; };
A key interface definition is the SVGSVGElement interface, which is the interface that corresponds to the ‘svg’ element. This interface contains various miscellaneous commonly-used utility methods, such as matrix operations and the ability to control the time of redraw on visual rendering devices.
SVGSVGElement implements ViewCSS and DocumentCSS to provide access to the computed values of properties and the override style sheet as described in DOM Level 2 Style [DOM2STYLE].
Does it make sense for SVGSVGElement to implement ViewCSS and DocumentCSS? Shouldn't the former be on Window and the latter on Document or SVGDocument?
interface SVGSVGElement : SVGGraphicsElement { readonly attribute SVGAnimatedLength x; readonly attribute SVGAnimatedLength y; readonly attribute SVGAnimatedLength width; readonly attribute SVGAnimatedLength height; readonly attribute SVGRect viewport; readonly attribute float pixelUnitToMillimeterX; readonly attribute float pixelUnitToMillimeterY; readonly attribute float screenPixelToMillimeterX; readonly attribute float screenPixelToMillimeterY; readonly attribute boolean useCurrentView; readonly attribute SVGViewSpec currentView; attribute float currentScale; readonly attribute SVGPoint currentTranslate; unsigned long suspendRedraw(unsigned long maxWaitMilliseconds); void unsuspendRedraw(unsigned long suspendHandleID); void unsuspendRedrawAll(); void forceRedraw(); void pauseAnimations(); void unpauseAnimations(); boolean animationsPaused(); float getCurrentTime(); void setCurrentTime(float seconds); NodeList getIntersectionList(SVGRect rect, SVGElement referenceElement); NodeList getEnclosureList(SVGRect rect, SVGElement referenceElement); boolean checkIntersection(SVGElement element, SVGRect rect); boolean checkEnclosure(SVGElement element, SVGRect rect); void deselectAll(); SVGNumber createSVGNumber(); SVGLength createSVGLength(); SVGAngle createSVGAngle(); SVGPoint createSVGPoint(); SVGMatrix createSVGMatrix(); SVGRect createSVGRect(); SVGTransform createSVGTransform(); SVGTransform createSVGTransformFromMatrix(SVGMatrix matrix); Element getElementById(DOMString elementId); }; SVGSVGElement implements ViewCSS; SVGSVGElement implements DocumentCSS; SVGSVGElement implements SVGFitToViewBox; SVGSVGElement implements SVGZoomAndPan;
The position and size of the viewport (implicit or explicit) that corresponds to this ‘svg’ element. When the user agent is actually rendering the content, then the position and size values represent the actual values when rendering. The position and size values are unitless values in the coordinate system of the parent element. If no parent element exists (i.e., ‘svg’ element represents the root of the document tree), if this SVG document is embedded as part of another document (e.g., via the HTML ‘object’ element), then the position and size are unitless values in the coordinate system of the parent document. (If the parent uses CSS or XSL layout, then unitless values represent pixel units for the current CSS or XSL viewport, as described in the CSS2 specification.) If the parent element does not have a coordinate system, then the user agent should provide reasonable default values for this attribute.
Should this and the next three IDL attributes be removed? Are they implemented?
The definition of the initial view (i.e., before magnification and panning) of the current innermost SVG document fragment. The meaning depends on the situation:
The object itself and its contents are both read only.
The value of a transform property on the outermost svg element does not affect the value of this attribute.
When accessed on an ‘svg’ element that is not an outermost svg element, this attribute must return 1 as scaling factor.
The value of a transform property on the outermost svg element does not affect the value of this attribute.
When accessed on an ‘svg’ element that is not an outermost svg element, this attribute must return an SVGPoint at the coordinates (0, 0).
Should this method be neutered as suspendRedraw and friends have been? Do implementations actually support painting in the middle of a running script by calling this method?
pointer-events
’ processing.
pointer-events
’ processing.
pointer-events
’ processing.
pointer-events
’ processing.
What is a type-in bar? Do we need deselectAll
given
we have DOM Selection?
Creates an SVGTransform object outside of any document trees. The object is initialized to the given matrix transform (i.e., SVG_TRANSFORM_MATRIX). The values from the parameter matrix are copied, the matrix parameter is not adopted as SVGTransform::matrix.
Do we need this? If so, can we define it in terms of calling Document.getElementById and checking whether the returned element is within the subtree?
interface SVGGElement : SVGGraphicsElement { };
interface SVGDefsElement : SVGGraphicsElement { };
interface SVGDescElement : SVGElement { };
interface SVGTitleElement : SVGElement { };
interface SVGSymbolElement : SVGElement { }; SVGSymbolElement implements SVGFitToViewBox;
The SVGUseElement interface corresponds to the ‘use’ element.
interface SVGUseElement : SVGGraphicsElement { readonly attribute SVGAnimatedLength x; readonly attribute SVGAnimatedLength y; readonly attribute SVGAnimatedLength width; readonly attribute SVGAnimatedLength height; readonly attribute SVGElementInstance instanceRoot; readonly attribute SVGElementInstance animatedInstanceRoot; }; SVGUseElement implements SVGURIReference;
For each ‘use’ element, the SVG DOM maintains a shadow tree (the "instance tree") of objects of type SVGElementInstance. An SVGElementInstance represents a single node in the instance tree. The root object in the instance tree is pointed to by the instanceRoot attribute on the SVGUseElement object for the corresponding ‘use’ element.
If the ‘use’ element references a simple graphics element such as a ‘rect’, then there is only a single SVGElementInstance object, and the correspondingElement attribute on this SVGElementInstance object is the SVGRectElement that corresponds to the referenced ‘rect’ element.
If the ‘use’ element references a ‘g’ which contains two ‘rect’ elements, then the instance tree contains three SVGElementInstance objects, a root SVGElementInstance object whose correspondingElement is the SVGGElement object for the ‘g’, and then two child SVGElementInstance objects, each of which has its correspondingElement that is an SVGRectElement object.
If the referenced object is itself a ‘use’, or if there are ‘use’ subelements within the referenced object, the instance tree will contain recursive expansion of the indirect references to form a complete tree. For example, if a ‘use’ element references a ‘g’, and the ‘g’ itself contains a ‘use’, and that ‘use’ references a ‘rect’, then the instance tree for the original (outermost) ‘use’ will consist of a hierarchy of SVGElementInstance objects, as follows:
SVGElementInstance #1 (parentNode=null, firstChild=#2, correspondingElement is the 'g') SVGElementInstance #2 (parentNode=#1, firstChild=#3, correspondingElement is the other 'use') SVGElementInstance #3 (parentNode=#2, firstChild=null, correspondingElement is the 'rect')
interface SVGElementInstance : EventTarget { readonly attribute SVGElement correspondingElement; readonly attribute SVGUseElement correspondingUseElement; readonly attribute SVGElementInstance parentNode; readonly attribute SVGElementInstanceList childNodes; readonly attribute SVGElementInstance firstChild; readonly attribute SVGElementInstance lastChild; readonly attribute SVGElementInstance previousSibling; readonly attribute SVGElementInstance nextSibling; };
interface SVGElementInstanceList { readonly attribute unsigned long length; SVGElementInstance item(unsigned long index); };
The SVGImageElement interface corresponds to the ‘image’ element.
interface SVGImageElement : SVGGraphicsElement { readonly attribute SVGAnimatedLength x; readonly attribute SVGAnimatedLength y; readonly attribute SVGAnimatedLength width; readonly attribute SVGAnimatedLength height; readonly attribute SVGAnimatedPreserveAspectRatio preserveAspectRatio; }; SVGImageElement implements SVGURIReference;
interface SVGSwitchElement : SVGGraphicsElement { };
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, such as the DOM Element object that corresponds to an HTML ‘object’ element. Such DOM objects are often also required to implement the EmbeddingElement defined in the Window specification [WINDOW].
This interface is deprecated and may be dropped from future versions of
the SVG specification. Authors are suggested to use the
contentDocument
attribute on the EmbeddingElement
interface to obtain a referenced SVG document, if that interface is
available.
[NoInterfaceObject] interface GetSVGDocument { SVGDocument getSVGDocument(); };
This method must return the Document object embedded content in an embedding element, or null if there is no document.
Note that this is equivalent to fetching the value of the
EmbeddingElement::contentDocument
attribute of the embedding
element, if the EmbeddingElement interface is also implemented.
The author is advised to check that the document element of the returned
Document is indeed an ‘svg’ element instead of assuming
that that will always be the case.
SVG uses styling properties to describe many of its document parameters. Styling properties define how the graphics elements in the SVG content are to be rendered. SVG uses styling properties for the following:
SVG shares many of its styling properties with CSS [CSS21] and XSL [XSL]. Except for any additional SVG-specific rules explicitly mentioned in this specification, the normative definition of properties that are shared with CSS and XSL is the definition of the property from the CSS 2.1 specification [CSS21].
The following properties are shared between CSS 2.1 and SVG. Most of these properties are also defined in XSL:
This list needs to be updated. We should list all the properties we normative require support for, and which specification they are defined in.
font
’font-family
’font-size
’font-size-adjust
’font-stretch
’font-style
’font-variant
’font-weight
’clip
’, only applicable to outermost svg element.color
’, used to provide a potential indirect value
(currentColor) for the
‘fill
’,
‘stroke
’,
‘stop-color
’,
‘flood-color
’ and
‘lighting-color
’
properties.
(The SVG properties which support color allow a color
specification which is extended from CSS 2.1 to accommodate
color definitions in arbitrary color spaces. See Color profile
descriptions.)cursor
’display
’overflow
’, only applicable to
elements which establish a new viewport.visibility
’The following SVG properties are not defined in CSS 2.1. The complete normative definitions for these properties are found in this specification:
color-interpolation
’color-rendering
’fill
’fill-opacity
’fill-rule
’image-rendering
’marker
’marker-end
’marker-mid
’marker-start
’shape-rendering
’stroke
’stroke-dasharray
’stroke-dashoffset
’stroke-linecap
’stroke-linejoin
’stroke-miterlimit
’stroke-opacity
’stroke-width
’text-rendering
’A table that lists and summarizes the styling properties can be found in the Property Index.
Does this section add anything?
SVG has many usage scenarios, each with different needs. Here are three common usage scenarios:
SVG content used as an exchange format (style sheet language-independent):
In some usage scenarios, reliable interoperability of SVG content across software tools is the main goal. Since support for a particular style sheet language is not guaranteed across all implementations, it is a requirement that SVG content can be fully specified without the use of a style sheet language.
SVG content generated as the output from XSLT:
XSLT offers the ability to take a stream of arbitrary XML content as input, apply potentially complex transformations, and then generate SVG content as output [XSLT]. XSLT can be used to transform XML data extracted from databases into an SVG graphical representation of that data. It is a requirement that fully specified SVG content can be generated from XSLT.
SVG content styled with CSS:
CSS is a widely implemented declarative language for assigning styling properties to XML content, including SVG [CSS21]. It represents a combination of features, simplicity and compactness that makes it very suitable for many applications of SVG. It is a requirement that CSS styling can be applied to SVG content.
Styling properties can be assigned to SVG elements in the following two ways:
Presentation attributes
Styling properties can be assigned using SVG's presentation attributes. For each styling property defined in this specification, there is a corresponding XML presentation attribute available on all relevant SVG elements. Detailed information on the presentation attributes can be found in Specifying properties using the presentation attributes.
The presentation attributes are style sheet language independent and thus are applicable to usage scenario 1 above (i.e., tool interoperability). Because it is straightforward to assign values to XML attributes from XSLT, the presentation attributes are well-suited to usage scenario 2 above (i.e., SVG generation from XSLT). (See Styling with XSL below.)
Conforming SVG Interpreters and Conforming SVG Viewers are required to support SVG's presentation attributes.
CSS Stylesheets
To support usage scenario 3 above, SVG content can be styled with CSS. For more information, see Styling with CSS.
Conforming SVG Interpreters and Conforming SVG Viewers that support CSS styling of generic (i.e., text-based) XML content are required to also support CSS styling of SVG content.
For each styling property defined in this specification (see
Property Index), there is a
corresponding XML attribute (the presentation attribute) with the same
name that is available on all relevant SVG elements. For
example, SVG has a ‘fill
’ property that defines how
to paint the interior of a shape. There is a corresponding
presentation attribute with the same name (i.e., ‘fill’) that can be used to specify a
value for the ‘fill
’ property on a given
element.
We should state that for each property defined in this specification, plus for each in a list here for properties in other specifications, there exists a presentation attribute.
Do we plan to grow a presentation attribute for each new CSS property that we support?
The following example shows how the ‘fill
’ and
‘stroke
’ properties can be specified on a ‘rect’ using the
‘fill’ and
‘stroke’ presentation attributes. The
rectangle will be filled with red and outlined with blue:
<?xml version="1.0" standalone="no"?> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="10cm" height="5cm" viewBox="0 0 1000 500"> <rect x="200" y="100" width="600" height="300" fill="red" stroke="blue" stroke-width="3"/> </svg>
The presentation attributes offer the following advantages:
In some situations, SVG content that uses the presentation attributes has potential limitations versus SVG content that is styled with a style sheet language such as CSS (see Styling with CSS). In other situations, such as when an XSLT style sheet generates SVG content from semantically rich XML source files, the limitations below may not apply. Depending on the situation, some of the following potential limitations may or may not apply to the presentation attributes:
For user agents that support CSS, the presentation attributes must be translated to corresponding CSS style rules according to rules described in Precedence of non-CSS presentational hints ([CSS21], section 6.4.4), with the additional clarification that the presentation attributes are conceptually inserted into a new author style sheet which is the first in the author style sheet collection. The presentation attributes thus will participate in the CSS 2.1 cascade as if they were replaced by corresponding CSS style rules placed at the start of the author style sheet with a specificity of zero. In general, this means that the presentation attributes have lower priority than other CSS style rules specified in author style sheets or ‘style’ attributes.
User agents that do not support CSS must ignore any CSS style rules defined in CSS style sheets and ‘style’ attributes. In this case, the CSS cascade does not apply. (Inheritance of properties, however, does apply. See Property inheritance.)
An !important declaration ([CSS21], section 6.4.2) within a presentation attribute definition is an invalid value.
Animation of presentation attributes is equivalent to animating the corresponding property. Thus, the same effect occurs from animating the presentation attribute with attributeType="XML" as occurs with animating the corresponding property with attributeType="CSS" (see ‘attributeType’).
How much do we really need to mention XSLT?
Probably the only thing worth mentioning is that <?xml-stylesheet?>
can be used in an XML serialized SVG document (not that we
require support for this, though).
XSL style sheets [XSLT] [XSLT2] define how to transform XML content into something else, usually other XML. When XSLT is used in conjunction with SVG, sometimes SVG content will serve as both input and output for XSL style sheets. Other times, XSL style sheets will take non-SVG content as input and generate SVG content as output.
The following example uses an external XSL style sheet to
transform SVG content into modified SVG content (see Referencing
external style sheets). The style sheet sets the
‘fill
’ and ‘stroke
’ properties on all
rectangles to red and blue, respectively:
mystyle.xsl <?xml version="1.0" standalone="no"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:svg="http://www.w3.org/2000/svg"> <xsl:output method="xml" encoding="utf-8"> <!-- Add version to topmost 'svg' element --> <xsl:template match="/svg:svg"> <xsl:copy> <xsl:copy-of select="@*"/> <xsl:attribute name="version">1.1</xsl:attribute> <xsl:apply-templates/> </xsl:copy> </xsl:template> <!-- Add styling to all 'rect' elements --> <xsl:template match="svg:rect"> <xsl:copy> <xsl:copy-of select="@*"/> <xsl:attribute name="fill">red</xsl:attribute> <xsl:attribute name="stroke">blue</xsl:attribute> <xsl:attribute name="stroke-width">3</xsl:attribute> </xsl:copy> </xsl:template> </xsl:stylesheet> SVG file to be transformed by mystyle.xsl <?xml version="1.0" standalone="no"?> <?xml-stylesheet href="mystyle.xsl" type="application/xml"?> <svg xmlns="http://www.w3.org/2000/svg" width="10cm" height="5cm"> <rect x="2cm" y="1cm" width="6cm" height="3cm"/> </svg> SVG content after applying mystyle.xsl <?xml version="1.0" encoding="utf-8"?> <svg xmlns="http://www.w3.org/2000/svg" width="10cm" height="5cm" version="1.1"> <rect x="2cm" y="1cm" width="6cm" height="3cm" fill="red" stroke="blue" stroke-width="3"/> </svg>
SVG implementations that support CSS are required to support the following:
The following example shows the use of an external CSS style
sheet to set the ‘fill
’ and ‘stroke
’ properties on all
rectangles to red and blue, respectively:
mystyle.css rect { fill: red; stroke: blue; stroke-width: 3 } SVG file referencing mystyle.css <?xml version="1.0" standalone="no"?> <?xml-stylesheet href="mystyle.css" type="text/css"?> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="10cm" height="5cm" viewBox="0 0 1000 500"> <rect x="200" y="100" width="600" height="300"/> </svg>
View this
example as SVG (SVG-enabled browsers only)
CSS style sheets can be embedded within SVG content inside of a ‘style’ element. The following example uses an internal CSS style sheet to achieve the same result as the previous example:
<?xml version="1.0" standalone="no"?> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="10cm" height="5cm" viewBox="0 0 1000 500"> <defs> <style type="text/css"><![CDATA[ rect { fill: red; stroke: blue; stroke-width: 3 } ]]></style> </defs> <rect x="200" y="100" width="600" height="300"/> </svg>
Note how the CSS style sheet is placed within a CDATA
construct (i.e., <![CDATA[ ... ]]>
). Placing
internal CSS style sheets within CDATA
blocks is
sometimes necessary since CSS style sheets can include
characters, such as ">", which conflict with XML parsers.
Even if a given style sheet does not use characters that
conflict with XML parsing, it is highly recommended that
internal style sheets be placed inside CDATA
blocks.
Implementations that support CSS are also required to support CSS inline style. Similar to the ‘style’ attribute in HTML, CSS inline style can be declared within a ‘style’ attribute in SVG by specifying a semicolon-separated list of property declarations, where each property declaration has the form "name: value". Note that property declarations inside the ‘style’ attribute must follow CSS style rules, see The 'style' attribute.
The following example shows how the
‘fill
’ and ‘stroke
’ properties can be specified
on a ‘rect’ using the ‘style’ attribute. Just like the
previous example, the rectangle will be filled with red and
outlined with blue:
<?xml version="1.0" standalone="no"?> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="10cm" height="5cm" viewBox="0 0 1000 500"> <rect x="200" y="100" width="600" height="300" style="fill: red; stroke: blue; stroke-width: 3"/> </svg>
In an SVG user agent that supports CSS style sheets, the following facilities from CSS 2.1 must be supported:
SVG defines an @color-profile at-rule ([CSS21], section 4.1.5) for defining color profiles so that ICC color profiles can be applied to CSS-styled SVG content.
Note the following about relative URIs and external CSS style sheets: The CSS 2.1 specification says ([CSS21], section 4.3.4) that relative URIs (as defined in Uniform Resource Identifiers (URI): Generic Syntax [RFC3986]) within style sheets are resolved such that the base URI is that of the style sheet, not that of the referencing document.
Property declarations via presentation attributes are expressed in XML [XML10], which is case-sensitive. CSS property declarations specified either in CSS style sheets or in a ‘style’ attribute, on the other hand, are generally case-insensitive with some exceptions ([CSS21], section 4.1.3).
Because presentation attributes are expressed as XML
attributes, their names are case-sensitive and must be
given exactly as they are defined.
When using a presentation attribute to specify a value for the
‘fill
’ property, the presentation attribute must be
be specified as fill="…" and not
fill="…" or Fill="…". Keyword
values, such as italic in
font-style="italic",
are also case-sensitive and must be specified using the exact
case used in the specification which defines the given keyword.
For example, the keyword sRGB
must have lowercase "s" and uppercase "RGB".
Property declarations within CSS style sheets or in a ‘style’ attribute must only conform to CSS rules, which are generally more lenient with regard to case sensitivity. However, to promote consistency across the different ways for expressing styling properties, it is strongly recommended that authors use the exact property names (usually, lowercase letters and hyphens) as defined in the relevant specification and express all keywords using the same case as is required by presentation attributes and not take advantage of CSS's ability to ignore case.
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) |
SVG shares various relevant properties and approaches common to CSS and XSL, plus the semantics of many of the processing rules.
SVG shares the following facilities with CSS and XSL:
External style sheets are referenced using the mechanism documented in Associating Style Sheets with XML documents Version 1.0 [XML-SS].
We should suggest @import
as a means for
referencing external CSS style sheets that will also work in an HTML5
document.
Where is it defined that an HTML ‘link’ element can cause a style sheet to be loaded and applied to SVG content? Should we allow (an SVG or HTML namespace) ‘link’ element in an SVG document fragment?
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 (see HTML's ‘style’ element).
Attribute definitions:
Name | Value | Lacuna value | Animatable |
---|---|---|---|
type | content-type | text/css | no |
This attribute specifies the style sheet language of the element's contents. The style sheet language is specified as a content type (e.g., "text/css"), as per MIME Part Two: Media Types [RFC2046]. If the attribute is not specified, then the style sheet language is assumed to be CSS.
Name | Value | Lacuna value | Animatable |
---|---|---|---|
media | media | (none) | no |
This attribute specifies the intended destination medium for style information. It may be a single media descriptor or a comma-separated list. The default value for this attribute is "all". The set of recognized media-descriptors are the list of media types recognized by CSS 2.1 ([CSS21], section 7.3).
Name | Value | Lacuna value | Animatable |
---|---|---|---|
title | advisory-title | (none) | no |
(For compatibility with HTML 4 [HTML4].) This attribute specifies an advisory title for the ‘style’ element.
The syntax of style data depends on the style sheet language.
Some style sheet languages might allow a wider variety of rules in the ‘style’ element than in the ‘style’. For example, with CSS, rules can be declared within a ‘style’ element that cannot be declared within a ‘style’ attribute.
An example showing the ‘style’ element is provided above (see example).
Attribute definitions:
The ‘class’ attribute assigns one or more class names to an element. The element may be said to belong to these classes. A class name may be shared by several element instances. The ‘class’ attribute has several roles:
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>
In an SVG user agent that supports CSS styling, 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 { color: green } text.warning { color: yellow } text.error { color: red }
The ‘style’ attribute allows per-element style rules to be specified directly on a given element. When CSS styling is used, CSS inline style is specified by including semicolon-separated property declarations of the form "name : value" within the ‘style’ attribute. Property declarations must follow CSS style rules thus CSS defined properties (e.g. 'font-size') when having a <length> value must include a unit (for non-zero values). See SVG's styling properties for a list of CSS defined properties.
Attribute definitions:
The style attribute may be used to apply a particular style to an individual SVG element. If the style will be reused for several elements, authors should use the ‘style’ element to regroup that information. For optimal flexibility, authors should define styles in external style sheets.
An example showing the ‘style’ attribute is provided above (see example).
Whether or not the user agent supports CSS, property inheritance in SVG follows the property inheritance rules defined in the CSS 2.1 specification. The normative definition for property inheritance is the Inheritance section of the CSS 2.1 specification ([CSS21], section 6.2).
The definition of each property indicates whether the property can inherit the value of its parent.
In SVG, as in CSS 2.1, most elements inherit
computed values
([CSS21], section 6.1.2).
For cases where something other than
computed values are inherited, the property definition will
describe the inheritance rules. For specified values
([CSS21], section 6.1.1)
which are expressed in user units, in
pixels (e.g., 20px) or in absolute values,
the computed value equals the specified
value. For specified values which use certain relative units
(i.e., em, ex and percentages), the computed
value will have the same units as the value to which it is
relative. Thus, if the parent element has a ‘font-size
’ of
10pt and the current
element has a ‘font-size
’ of 120%,
then the computed value for ‘font-size
’ on the current element
will be 12pt. In cases where the referenced value for
relative units is not expressed in any of the standard SVG
units (i.e., CSS units or user units), such as when a
percentage is used relative to the current viewport or an
object bounding box, then the computed value will be in user
units.
Note that SVG has some facilities wherein a property which
is specified on an ancestor element might effect its descendant
element, even if the descendant element has a different
assigned value for that property. For example, if a ‘clip-path
’
property is specified on an ancestor element, and the current element has a
‘clip-path
’ of none, the
ancestor's clipping path
still applies to the current element because the semantics of
SVG state that the clipping path used on a given element is the
intersection of all clipping paths specified on itself and all
ancestor elements. The key concept is that property assignment
(with possible property inheritance) happens first. After
properties values have been assigned to the various elements,
then the user agent applies the semantics of each assigned
property, which might result in the property assignment of an
ancestor element affecting the rendering of its
descendants.
The following define the scope/range of style sheets:
As part of unifying HTML's and SVG's ‘style’ element, we should allow and mention scoped style sheets here.
The user agent shall maintain a user agent style sheet ([CSS21], section 6.4) for elements in the SVG namespace for visual media ([CSS21], section 7.3.1). The user agent style sheet below is expressed using CSS syntax; however, user agents are required to support the behavior that corresponds to this default style sheet even if CSS style sheets are not supported in the user agent:
svg, symbol, image, marker, pattern, foreignObject { overflow: hidden } svg { width:attr(width); height:attr(height) }
This needs to be reviewed. It should at least
use @namespace
to cause the rules to match only
SVG elements. attr(width)
won't do the right
thing if the ‘width’ attribute does
not use a unit. And what about when the attributes are being
animated? Presumably attr()
doesn't look at animated
values.
The first line of the above user agent style sheet will
cause the initial
clipping path to be established at the bounds of the initial viewport.
Furthermore, it will cause new clipping paths to be established
at the bounds of the listed elements, all of which are elements that
establish a new viewport. (Refer to the description of
SVG's use of the ‘overflow
’ property for more
information.)
The second line of the above user agent style sheet will cause the ‘width’ and ‘height’ attributes on the ‘svg’ element to be used as the default values for the 'width' and 'height' properties during layout ([CSS21], chapter 9).
For the purposes of aural media, SVG represents a stylable XML grammar. In user agents that support CSS aural style sheets, aural style properties ([CSS21], chapter 19) can be applied as defined in CSS 2.1.
Aural style properties can be applied to any SVG element that can contain character data content, including ‘desc’ ‘title’ ‘tspan’, ‘tref’, ‘altGlyph’ and ‘textPath’. On user agents that support aural style sheets, the following CSS 2.1 properties can be applied:
The above list misses ‘a’, which can be within a ‘text’ element. Is there a conformance class in CSS we can link to for "user agents that support aural style sheets"? Are aural properties still relevant?
Aural property | Definition in [CSS21] |
---|---|
‘azimuth’ | Section A.8 |
‘cue’ | Section A.6 |
‘cue-after’ | Section A.6 |
‘cue-before’ | Section A.6 |
‘elevation’ | Section A.8 |
‘pause’ | Section A.5 |
‘pause-after’ | Section A.5 |
‘pause-before’ | Section A.5 |
‘pitch’ | Section A.9 |
‘pitch-range’ | Section A.9 |
‘play-during’ | Section A.7 |
‘richness’ | Section A.9 |
‘speak’ | Section A.4 |
‘speak-header’ | Section A.11.1 |
‘speak-numeral’ | Section A.10 |
‘speak-punctuation’ | Section A.10 |
‘speech-rate’ | Section A.9 |
‘stress’ | Section A.9 |
‘voice-family’ | Section A.9 |
‘volume’ | Section A.3 |
For user agents that support aural style sheets and also support DOM Level 2 Core, the user agent is required to support the DOM interfaces defined in Document Object Model CSS ([DOM2STYLE], chapter 2) that correspond to aural properties. (See Relationship with DOM2 CSS object model.)
interface SVGStyleElement : SVGElement { attribute DOMString type; attribute DOMString media; attribute DOMString title; };
For all media, the SVG canvas describes "the space where the SVG content is rendered." The canvas is infinite for each dimension of the space, but rendering occurs relative to a finite rectangular region of the canvas. This finite rectangular region is called the SVG viewport. For visual media ([CSS21], section 7.3.1) the SVG viewport is the viewing area where the user sees the SVG content.
The size of the SVG viewport (i.e., its width and height) is determined by a negotiation process (see Establishing the size of the initial viewport) between the SVG document fragment and its parent (real or implicit). Once that negotiation process is completed, the SVG user agent is provided the following information:
Why are real world units relevant? Shouldn't we just be relying on CSS' fixed ratio of mm to px units?
Using the above information, the SVG user agent determines the viewport, an initial viewport coordinate system and an initial user coordinate system such that the two coordinates systems are identical. Both coordinates systems are established such that the origin matches the origin of the viewport (for the root viewport, the viewport origin is at the top/left corner), and one unit in the initial coordinate system equals one "pixel" in the viewport. (See Initial coordinate system.) The viewport coordinate system is also called viewport space and the user coordinate system is also called user space.
Lengths in SVG can be specified as:
The supported length unit identifiers are: em, ex, px, pt, pc, cm, mm, in, and percentages.
A new user space (i.e., a new current coordinate system) can be established at any place within an SVG document fragment by specifying transformations in the form of transformation matrices or simple transformation operations such as rotation, skewing, scaling and translation. Establishing new user spaces via coordinate system transformations are fundamental operations to 2D graphics and represent the usual method of controlling the size, position, rotation and skew of graphic objects.
New viewports also can be established. By establishing a new viewport, you can redefine the meaning of percentages units and provide a new reference rectangle for "fitting" a graphic into a particular rectangular area. ("Fit" means that a given graphic is transformed in such a way that its bounding box in user space aligns exactly with the edges of a given viewport.)
Do we need to port over some more up-to-date definitions of sizing from SVG Tiny 1.2?
The SVG user agent negotiates with its parent user agent to determine the viewport into which the SVG user agent can render the document. In some circumstances, SVG content will be embedded (by reference or inline) within a containing document. This containing document might include attributes, properties and/or other parameters (explicit or implicit) which specify or provide hints about the dimensions of the viewport for the SVG content. SVG content itself optionally can provide information about the appropriate viewport region for the content via the ‘width’ and ‘height’ XML attributes on the outermost svg element. The negotiation process uses any information provided by the containing document and the SVG content itself to choose the viewport location and size.
Talking about a "parent user agent" really makes this sound like we have a separate plugin SVG implementation communicating with a browser hosting the plugin. These days, it's going to be the same user agent.
The ‘width’ attribute on the outermost svg element establishes the viewport's width, unless the following conditions are met:
Under these conditions, the positioning properties establish the viewport's width.
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 establish the viewport's height; otherwise, the ‘height’ attribute on the outermost svg element establishes the viewport's height.
If the ‘width’ or ‘height’ 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" version="1.1"> <path d="M100,100 Q200,400,300,100"/> <!-- rest of SVG graphic would go here --> </svg> </parent>
The initial clipping path for the SVG document fragment is established according to the rules described in The initial clipping path.
For the outermost svg element, the SVG user agent determines an initial viewport coordinate system and an initial user coordinate system such that the two coordinates systems are identical. The origin of both coordinate systems is at the origin of the viewport, and one unit in the initial coordinate system equals one "pixel" (i.e., a px unit as defined in CSS 2.1 ([CSS21], section 4.3.2) in the viewport. In most cases, such as stand-alone SVG documents or SVG document fragments embedded (by reference or inline) within XML 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) has 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 XML documents using CSS 2.1 compatible px units, then the SVG user agent should get its initial value for the size of a px unit in real world units to match the value used for other XML 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>
A new user space (i.e., a new current coordinate system) can
be established by specifying transformations in the form of a ‘transform
’
property on a container element or graphics element or a
‘viewBox’ attribute on an
‘svg’,
‘symbol’,
‘marker’,
‘pattern’ and the
‘view’ element.
The ‘transform
’ property and ‘viewBox’ attribute transform user
space coordinates and lengths on sibling attributes on the
given element (see
effect of the ‘transform’ attribute on sibling attributes
and effect
of the ‘viewBox’ attribute on
sibling attributes) and all of its descendants.
Transformations can be nested, in which case the effect of the
transformations are cumulative.
The section "effect of the transform attribute on sibling attributes"
has been removed since we now reference the ‘transform
’ property, but we probably
should still include a similar section on how the property affects attributes on the
element.
Example OrigCoordSys below shows a document without transformations. The text string is specified in the initial coordinate system.
<?xml version="1.0" standalone="no"?> <svg width="400px" height="150px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <desc>Example OrigCoordSys - Simple transformations: original picture</desc> <g fill="none" stroke="black" stroke-width="3" > <!-- Draw the axes of the original coordinate system --> <line x1="0" y1="1.5" x2="400" y2="1.5" /> <line x1="1.5" y1="0" x2="1.5" y2="150" /> </g> <g> <text x="30" y="30" font-size="20" font-family="Verdana" > ABC (orig coord system) </text> </g> </svg>
Example NewCoordSys establishes a new user coordinate system by specifying transform="translate(50,50)" on the third ‘g’ element below. The new user coordinate system has its origin at location (50,50) in the original coordinate system. The result of this transformation is that the coordinate (30,30) in the new user coordinate system gets mapped to coordinate (80,80) in the original coordinate system (i.e., the coordinates have been translated by 50 units in X and 50 units in Y).
<?xml version="1.0" standalone="no"?> <svg width="400px" height="150px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <desc>Example NewCoordSys - New user coordinate system</desc> <g fill="none" stroke="black" stroke-width="3" > <!-- Draw the axes of the original coordinate system --> <line x1="0" y1="1.5" x2="400" y2="1.5" /> <line x1="1.5" y1="0" x2="1.5" y2="150" /> </g> <g> <text x="30" y="30" font-size="20" font-family="Verdana" > ABC (orig coord system) </text> </g> <!-- Establish a new coordinate system, which is shifted (i.e., translated) from the initial coordinate system by 50 user units along each axis. --> <g transform="translate(50,50)"> <g fill="none" stroke="red" stroke-width="3" > <!-- Draw lines of length 50 user units along the axes of the new coordinate system --> <line x1="0" y1="0" x2="50" y2="0" stroke="red" /> <line x1="0" y1="0" x2="0" y2="50" /> </g> <text x="30" y="30" font-size="20" font-family="Verdana" > ABC (translated coord system) </text> </g> </svg>
Example RotateScale illustrates simple rotate and scale transformations. The example defines two new coordinate systems:
<?xml version="1.0" standalone="no"?> <svg width="400px" height="120px" version="1.1" xmlns="http://www.w3.org/2000/svg"> <desc>Example RotateScale - Rotate and scale transforms</desc> <g fill="none" stroke="black" stroke-width="3" > <!-- Draw the axes of the original coordinate system --> <line x1="0" y1="1.5" x2="400" y2="1.5" /> <line x1="1.5" y1="0" x2="1.5" y2="120" /> </g> <!-- Establish a new coordinate system whose origin is at (50,30) in the initial coord. system and which is rotated by 30 degrees. --> <g transform="translate(50,30)"> <g transform="rotate(30)"> <g fill="none" stroke="red" stroke-width="3" > <line x1="0" y1="0" x2="50" y2="0" /> <line x1="0" y1="0" x2="0" y2="50" /> </g> <text x="0" y="0" font-size="20" font-family="Verdana" fill="blue" > ABC (rotate) </text> </g> </g> <!-- Establish a new coordinate system whose origin is at (200,40) in the initial coord. system and which is scaled by 1.5. --> <g transform="translate(200,40)"> <g transform="scale(1.5)"> <g fill="none" stroke="red" stroke-width="3" > <line x1="0" y1="0" x2="50" y2="0" /> <line x1="0" y1="0" x2="0" y2="50" /> </g> <text x="0" y="0" font-size="20" font-family="Verdana" fill="blue" > ABC (scale) </text> </g> </g> </svg>
Example Skew defines two coordinate systems which are skewed relative to the origin coordinate system.
<?xml version="1.0" standalone="no"?> <svg width="400px" height="120px" version="1.1" xmlns="http://www.w3.org/2000/svg"> <desc>Example Skew - Show effects of skewX and skewY</desc> <g fill="none" stroke="black" stroke-width="3" > <!-- Draw the axes of the original coordinate system --> <line x1="0" y1="1.5" x2="400" y2="1.5" /> <line x1="1.5" y1="0" x2="1.5" y2="120" /> </g> <!-- Establish a new coordinate system whose origin is at (30,30) in the initial coord. system and which is skewed in X by 30 degrees. --> <g transform="translate(30,30)"> <g transform="skewX(30)"> <g fill="none" stroke="red" stroke-width="3" > <line x1="0" y1="0" x2="50" y2="0" /> <line x1="0" y1="0" x2="0" y2="50" /> </g> <text x="0" y="0" font-size="20" font-family="Verdana" fill="blue" > ABC (skewX) </text> </g> </g> <!-- Establish a new coordinate system whose origin is at (200,30) in the initial coord. system and which is skewed in Y by 30 degrees. --> <g transform="translate(200,30)"> <g transform="skewY(30)"> <g fill="none" stroke="red" stroke-width="3" > <line x1="0" y1="0" x2="50" y2="0" /> <line x1="0" y1="0" x2="0" y2="50" /> </g> <text x="0" y="0" font-size="20" font-family="Verdana" fill="blue" > ABC (skewY) </text> </g> </g> </svg>
Transformations can be nested to any level. The effect of
nested transformations is to post-multiply (i.e., concatenate)
the subsequent transformation matrices onto previously defined
transformations:
For each given element, the accumulation of all
transformations that have been defined on the given element and
all of its ancestors up to and including the element that
established the current viewport (usually, the ‘svg’
element which is the most
immediate ancestor to the given element) is called the
current transformation matrix or
CTM. The CTM thus represents the
mapping of current user coordinates to viewport
coordinates:
Example Nested illustrates nested transformations.
<?xml version="1.0" standalone="no"?> <svg width="400px" height="150px" version="1.1" xmlns="http://www.w3.org/2000/svg"> <desc>Example Nested - Nested transformations</desc> <g fill="none" stroke="black" stroke-width="3" > <!-- Draw the axes of the original coordinate system --> <line x1="0" y1="1.5" x2="400" y2="1.5" /> <line x1="1.5" y1="0" x2="1.5" y2="150" /> </g> <!-- First, a translate --> <g transform="translate(50,90)"> <g fill="none" stroke="red" stroke-width="3" > <line x1="0" y1="0" x2="50" y2="0" /> <line x1="0" y1="0" x2="0" y2="50" /> </g> <text x="0" y="0" font-size="16" font-family="Verdana" > ....Translate(1) </text> <!-- Second, a rotate --> <g transform="rotate(-45)"> <g fill="none" stroke="green" stroke-width="3" > <line x1="0" y1="0" x2="50" y2="0" /> <line x1="0" y1="0" x2="0" y2="50" /> </g> <text x="0" y="0" font-size="16" font-family="Verdana" > ....Rotate(2) </text> <!-- Third, another translate --> <g transform="translate(130,160)"> <g fill="none" stroke="blue" stroke-width="3" > <line x1="0" y1="0" x2="50" y2="0" /> <line x1="0" y1="0" x2="0" y2="50" /> </g> <text x="0" y="0" font-size="16" font-family="Verdana" > ....Translate(3) </text> </g> </g> </g> </svg>
In the example above, the CTM within the third nested
transformation (i.e., the transform="translate(130,160)")
consists of the concatenation of the three transformations, as
follows:
Name: | transform |
---|---|
Animatable: | yes |
Do we need this blue box, and if so, should we expand it to
include all of the property definition information? Some sections (such as
for ‘color’) do not have the blue box.
Others, like the one for ‘white-space
’, have all the information from
the CSS specification it comes from. Regardless, I think we don't need
to mention whether the property is animatable since all properties are
animatable.
The term <transform-list> used by this specification is equivalent to a list of <transform-functions>, the value of the ‘transform
’
property.
transform
’ property and the value of <transform-functions> [CSS3TRANSFORMS].It is often desirable to specify that a given set of graphics stretch to fit a particular container element. The ‘viewBox’ attribute provides this capability.
All elements that establish a new viewport (see elements that establish viewports), plus the ‘marker’, ‘pattern’ and ‘view’ elements have attribute ‘viewBox’. 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, which specify a rectangle in user space which should be mapped to the bounds of the viewport established by the given element, taking into account attribute ‘preserveAspectRatio’. If specified, an additional transformation is applied to all descendants of the given element to achieve the specified effect.
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 viewport.
<?xml version="1.0" standalone="no"?> <svg width="300px" height="200px" version="1.1" 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 viewport no matter what size the viewport is.</desc> <!-- This rectangle goes from (0,0) to (1500,1000) in user space. 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 viewport --> <text x="100" y="600" font-size="200" font-family="Verdana" > Stretch to fit </text> </svg>
Rendered into viewport with width=300px, height=200px |
Rendered into viewport with width=150px, height=200px |
|
---|---|---|
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 user space to the bounds of a designated region (often, the viewport). To achieve the effect of the example on the left, with 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 a 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" version="1.1" 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 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 a 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" version="1.1" xmlns="http://www.w3.org/2000/svg"> <g transform="scale(0.1 0.2)"> <!-- Rest of document goes here --> </g> </svg>
(Note: 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>.)
Unlike the
‘transform
’ property (see
effect of the ‘transform’ attribute on sibling attributes),
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 attributes
‘width’,
‘height’ and ‘viewBox’,
the ‘width’ and ‘height’ attributes
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.
Link to the "effect of the 'transform' attribute on sibling attributes" in the above paragraph needs to be update.
For the ‘viewBox’ attribute:
Animatable: yes.
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 viewport. In other cases, it is desirable that uniform scaling be used for the purposes of preserving the aspect ratio of the graphics.
Attribute preserveAspectRatio="[defer] <align> [<meetOrSlice>]", which is available for all elements that establish a new viewport (see elements that establish viewports), plus the ‘image’, ‘marker’, ‘pattern’ and ‘view’ elements, indicates whether or not to force uniform scaling.
For elements that establish a new viewport (see elements that establish 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.
If the value of ‘preserveAspectRatio’ on an ‘image’ element starts with 'defer' then the value of the ‘preserveAspectRatio’ attribute on the referenced content if present should be used. If the referenced content lacks a value for ‘preserveAspectRatio’ then the ‘preserveAspectRatio’ attribute should be processed as normal (ignoring 'defer'). For ‘preserveAspectRatio’ on all other elements the 'defer' portion of the attribute is ignored.
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 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:
meet (the default) - Scale the graphic such that:
In this case, if the aspect ratio of the graphic does not match the viewport, some of the viewport will extend beyond the bounds of the ‘viewBox’ (i.e., the area into which the ‘viewBox’ will draw will be smaller than the viewport).
slice - Scale the graphic such that:
In this case, if the aspect ratio of the ‘viewBox’ does not match the viewport, some of the ‘viewBox’ will extend beyond the bounds of the viewport (i.e., the area into which the ‘viewBox’ will draw is larger than the viewport).
Example PreserveAspectRatio illustrates the various options on ‘preserveAspectRatio’. To save space, XML entities have been defined for the three repeated graphic objects, the rectangle with the smile inside and the outlines of the two rectangles which have the same dimensions as the target viewports. The example creates several new viewports by including ‘svg’ sub-elements embedded inside the outermost svg element (see Establishing a new viewport).
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg [ <!ENTITY Smile " <rect x='.5' y='.5' width='29' height='39' fill='black' stroke='red'/> <g transform='translate(0, 5)'> <circle cx='15' cy='15' r='10' fill='yellow'/> <circle cx='12' cy='12' r='1.5' fill='black'/> <circle cx='17' cy='12' r='1.5' fill='black'/> <path d='M 10 19 A 8 8 0 0 0 20 19' stroke='black' stroke-width='2'/> </g> "> <!ENTITY Viewport1 "<rect x='.5' y='.5' width='49' height='29' fill='none' stroke='blue'/>"> <!ENTITY Viewport2 "<rect x='.5' y='.5' width='29' height='59' fill='none' stroke='blue'/>"> ]> <svg width="450px" height="300px" version="1.1" xmlns="http://www.w3.org/2000/svg"> <desc>Example PreserveAspectRatio - illustrates preserveAspectRatio attribute</desc> <rect x="1" y="1" width="448" height="298" fill="none" stroke="blue"/> <g font-size="9"> <text x="10" y="30">SVG to fit</text> <g transform="translate(20,40)">&Smile;</g> <text x="10" y="110">Viewport 1</text> <g transform="translate(10,120)">&Viewport1;</g> <text x="10" y="180">Viewport 2</text> <g transform="translate(20,190)">&Viewport2;</g> <g id="meet-group-1" transform="translate(100, 60)"> <text x="0" y="-30">--------------- meet ---------------</text> <g><text y="-10">xMin*</text>&Viewport1; <svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 30 40" width="50" height="30">&Smile;</svg></g> <g transform="translate(70,0)"><text y="-10">xMid*</text>&Viewport1; <svg preserveAspectRatio="xMidYMid meet" viewBox="0 0 30 40" width="50" height="30">&Smile;</svg></g> <g transform="translate(0,70)"><text y="-10">xMax*</text>&Viewport1; <svg preserveAspectRatio="xMaxYMax meet" viewBox="0 0 30 40" width="50" height="30">&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>&Viewport2; <svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 30 40" width="30" height="60">&Smile;</svg></g> <g transform="translate(50, 0)"><text y="-10">*YMid</text>&Viewport2; <svg preserveAspectRatio="xMidYMid meet" viewBox="0 0 30 40" width="30" height="60">&Smile;</svg></g> <g transform="translate(100, 0)"><text y="-10">*YMax</text>&Viewport2; <svg preserveAspectRatio="xMaxYMax meet" viewBox="0 0 30 40" width="30" height="60">&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>&Viewport2; <svg preserveAspectRatio="xMinYMin slice" viewBox="0 0 30 40" width="30" height="60">&Smile;</svg></g> <g transform="translate(50,0)"><text y="-10">xMid*</text>&Viewport2; <svg preserveAspectRatio="xMidYMid slice" viewBox="0 0 30 40" width="30" height="60">&Smile;</svg></g> <g transform="translate(100,0)"><text y="-10">xMax*</text>&Viewport2; <svg preserveAspectRatio="xMaxYMax slice" viewBox="0 0 30 40" width="30" height="60">&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>&Viewport1; <svg preserveAspectRatio="xMinYMin slice" viewBox="0 0 30 40" width="50" height="30">&Smile;</svg></g> <g transform="translate(70,0)"><text y="-10">*YMid</text>&Viewport1; <svg preserveAspectRatio="xMidYMid slice" viewBox="0 0 30 40" width="50" height="30">&Smile;</svg></g> <g transform="translate(140,0)"><text y="-10">*YMax</text>&Viewport1; <svg preserveAspectRatio="xMaxYMax slice" viewBox="0 0 30 40" width="50" height="30">&Smile;</svg></g> </g> </g> </svg>
This example should stop using DTD entities and use ‘use’ instead.
For the ‘preserveAspectRatio’ attribute:
Animatable: yes.
At any point in an SVG drawing, you can establish a new
viewport into which all contained graphics is drawn by
including an ‘svg’ element
inside SVG content. By establishing a new viewport, you also
implicitly establish a new viewport coordinate system, a new
user coordinate system, and, potentially, a new clipping path
(see the definition of the ‘overflow
’ property).
Additionally, there is a new meaning for percentage units
defined to be relative to the current viewport since a new
viewport has been established (see Units).
The bounds of the new viewport are defined by the ‘x’, ‘y’, ‘width’ and ‘height’ attributes on the element establishing the new 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 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 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 viewport.
Here is an example:
<?xml version="1.0" standalone="no"?> <svg width="4in" height="3in" version="1.1" xmlns="http://www.w3.org/2000/svg"> <desc>This SVG drawing embeds another one, thus establishing a new viewport </desc> <!-- The following statement establishing a new viewport and renders SVG drawing B into that viewport --> <svg x="25%" y="25%" width="50%" height="50%"> <!-- drawing B goes here --> </svg> </svg>
For an extensive example of creating new viewports, see Example PreserveAspectRatio.
The following elements establish new viewports:
Whether a new viewport also establishes a new additional
clipping path is determined by the value of the ‘overflow
’ property on the element
that establishes the new viewport. If a clipping path is
created to correspond to the new viewport, the clipping path's
geometry is determined by the value of the ‘clip
’ property. Also, see Clip to
viewport vs. clip to ‘viewBox’.
All coordinates and lengths in SVG can be specified with or without a unit identifier.
This is misleading – path data for example takes values that look like coordinates and lengths yet does not allow units.
When a coordinate or length value is a number without a unit identifier (e.g., "25"), then the given coordinate or length is assumed to be in user units (i.e., a value in the current user coordinate system). For example:
<text font-size="50">Text size is 50 user units</text>
Alternatively, a coordinate or length value can be expressed as a number followed by a unit identifier (e.g., "25cm" or "15em"). (Note that CSS defined properties used in a CSS style sheet or the ‘style’ attribute require units for non-zero lengths, see SVG's styling properties.) The list of unit identifiers in SVG matches the list of unit identifiers in CSS: em, ex, px, pt, pc, cm, mm and in. The <length> type can also have a percentage unit identifier. The following describes how the various unit identifiers are processed:
One px unit is defined to be equal to one user unit. Thus, a length of "5px" is the same as a length of "5".
Note that at initialization, a user unit in the the initial
coordinate system is equivalenced to the parent
environment's notion of a px unit. Thus, in the the initial
coordinate system, because the user coordinate system
aligns exactly with the parent's coordinate system, and
because often the parent's coordinate system aligns with
the device pixel grid, "5px" might actually map to 5
devices pixels. However, if there are any coordinate system
transformation due to the use of ‘transform
’ or
‘viewBox’ attributes, because
"5px" maps to 5 user units and because the coordinate
system transformations have resulted in a revised user
coordinate system, "5px" likely will not map to 5 device
pixels. As a result, in most circumstances, "px" units will
not map to the device pixel grid.
The other absolute unit identifiers from CSS (i.e., pt, pc, cm, mm, in) are all defined as an appropriate multiple of one px unit (which, according to the previous item, is defined to be equal to one user unit), based on what the SVG user agent determines is the size of a px unit (possibly passed from the parent processor or environment at initialization time). For example, suppose that the user agent can determine from its environment that "1px" corresponds to "0.2822222mm" (i.e., 90dpi). Then, for all processing of SVG content:
Note that use of px units or any other absolute unit identifiers can cause inconsistent visual results on different viewing environments since the size of "1px" may map to a different number of user units on different systems; thus, absolute units identifiers are only recommended for the ‘width’ and the ‘height’ on outermost svg elements and situations where the content contains no transformations and it is desirable to specify values relative to the device pixel grid or to a particular real world unit size.
That's wrong. 1px always corresponds to one user unit, and the "absolute" units must be interpreted as CSS says to, i.e. as fixed multiples of the CSS px, and not anything to do with the display's resolution. The recommendation to use the absolute units (apart from px) only for ‘width’ and ‘height’ on root ‘svg’ is a good one, however. Defining the size of a document in mm and then using mm units for shapes within it is going to give counterintuitive results, since they'll be converted to user units to resolve against the view box.
For percentage values that are defined to be relative to the size of viewport:
sqrt((actual-width)**2 +
(actual-height)**2)/sqrt(2)
.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" version="1.1"> <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>
The three rectangles on the left demonstrate the use of one of the absolute unit identifiers, the "in" unit (inch). The reference image above was generated on a 96dpi system (i.e., 1 inch = 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. (Note: on systems with different screen resolutions, the top and middle rectangles will likely be rendered at different sizes.) The bottom rectangle of the group illustrates what happens when values specified in inches are scaled.
The example needs to be changed in light of the issue above about absolute units.
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 viewport in
the user coordinate system for the 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.
The following elements offer the option of expressing coordinate values and lengths as fractions (and, in some cases, percentages) of the bounding box, by setting a specified attribute to 'objectBoundingBox' on the given element:
Need a line for ‘meshGradient’.
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. |
‘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. (See Inheritance
of Painting Properties. 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 for the applicable element and all of its descendants. The values minx, miny, maxx and maxy are determined by computing the maximum extent of the shape of the element in X and Y with respect to the user coordinate system for the applicable element. The bounding box is the tightest fitting rectangle aligned with the axes of the applicable element's user coordinate system that entirely encloses the applicable element and its descendants. The bounding box is computed exclusive of any values for clipping, masking, filter effects, opacity and stroke-width. For curved shapes, the bounding box encloses all portions of the shape, not just end points. For ‘text’ elements, for the purposes of the bounding box calculation, each glyph is treated as a separate graphics element. The calculations assume that all glyphs occupy the full glyph cell. For example, for horizontal text, the calculations assume that each glyph extends vertically to the full ascent and descent values for the font.
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.
SVG needs to specify how to calculate some intrinsic sizing properties to enable inclusion within other languages. The intrinsic width and height of the viewport of SVG content must be determined from the ‘width’ and ‘height’ attributes. If either of these are not specified, a value of '100%' must be assumed. Note: the ‘width’ and ‘height’ attributes are not the same as the CSS width and height properties. Specifically, percentage values do not provide an intrinsic width or height, and do not indicate a percentage of the containing block. Rather, once the viewport is established, they indicate the portion of the viewport that is actually covered by image data.
The intrinsic aspect ratio of the 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:
<svg xmlns="http://www.w3.org/2000/svg" version="1.2" baseProfile="tiny" width="10cm" height="5cm"> ... </svg>
In this example the intrinsic aspect ratio of the viewport is 2:1. The intrinsic width is 10cm and the intrinsic height is 5cm.
<svg xmlns="http://www.w3.org/2000/svg" version="1.2" baseProfile="tiny" width="100%" height="50%" viewBox="0 0 200 200"> ... </svg>
In this example the intrinsic aspect ratio of the rootmost 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.
<svg xmlns="http://www.w3.org/2000/svg" version="1.2" baseProfile="tiny" width="10cm" viewBox="0 0 200 200"> ... </svg>
In this case the intrinsic aspect ratio is 1:1.
<svg xmlns="http://www.w3.org/2000/svg" version="1.2" baseProfile="tiny" width="75%" height="10cm" viewBox="0 0 200 200"> ... </svg>
In this example, the intrinsic aspect ratio is 1:1.
In order to allow interoperability between SVG content generators and user agents dealing with maps encoded in SVG, the use of a common metadata definition for describing the coordinate system used to generate SVG documents is encouraged.
Such metadata must be added under the ‘metadata’ element of the topmost ‘svg’ element describing the map, consisting of an RDF description of the Coordinate Reference System definition used to generate the SVG map [RDF-PRIMER]. Note that the presence of this metadata does not affect the rendering of the SVG in any way; it merely provides added semantic value for applications that make use of combined maps.
The definition must be conformant to the XML grammar described in GML 3.2.1, an OpenGIS Standard for encoding common CRS data types in XML [GML]. In order to correctly map the 2-dimensional data used by SVG, the CRS must be of subtype ProjectedCRS or Geographic2dCRS. The first axis of the described CRS maps the SVG x-axis and the second axis maps the SVG y-axis.
The main purpose of such metadata is to indicate to the user agent
that two or more SVG documents can be overlayed or merged into a single
document. Obviously, if two maps reference the same Coordinate Reference
System definition and have the same SVG ‘transform
’ property
value then they can be overlayed without reprojecting the data. If
the maps reference different Coordinate Reference Systems and/or have
different SVG ‘transform
’ property values, then a specialized
cartographic user agent may choose to transform the coordinate data to
overlay the data. However, typical SVG user agents are not required
to perform these types of transformations, or even recognize the
metadata. It is described in this specification so that the connection
between geographic coordinate systems and the SVG coordinate system is
clear.
Do we need this section? Should we instead have a guide on how other specifications should re-use specific attributes or elements?
Attribute definition:
Specifies the affine transformation that has been applied to the map data. The syntax is identical to that described in The ‘transform’ property section.
Specifies that no supplemental affine transformation has been applied to the map data. Using this value has the same meaning as specifying the identity matrix, which in turn is just the same as not specifying the ‘svg:transform’ the attribute at all.
Animatable: no.
This attribute describes an optional additional affine
transformation that may have been applied during this
mapping. This attribute may be added to the OpenGIS
‘CoordinateReferenceSystem’ element. Note
that, unlike the ‘transform
’ property, it does not indicate that
a transformation is to be applied to the data within the file.
Instead, it simply describes the transformation that was already
applied to the data when being encoded in SVG.
There are three typical uses for the ‘svg:transform’ global attribute. These are described below and used in the examples.
Below is a simple example of the coordinate metadata, which describes the coordinate system used by the document via a URI.
<?xml version="1.0"?> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100" height="100" viewBox="0 0 1000 1000"> <desc>An example that references coordinate data.</desc> <metadata> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:crs="http://www.ogc.org/crs" xmlns:svg="http://www.w3.org/2000/svg"> <rdf:Description rdf:about=""> <!-- The Coordinate Reference System is described through a URI. --> <crs:CoordinateReferenceSystem svg:transform="rotate(-90)" rdf:resource="http://www.example.org/srs/epsg.xml#4326"/> </rdf:Description> </rdf:RDF> </metadata> <!-- The actual map content --> </svg>
The second example uses a well-known identifier to describe the coordinate system. Note that the coordinates used in the document have had the supplied transform applied.
<?xml version="1.0"?> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100" height="100" viewBox="0 0 1000 1000"> <desc>Example using a well known coordinate system.</desc> <metadata> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:crs="http://www.ogc.org/crs" xmlns:svg="http://www.w3.org/2000/svg"> <rdf:Description rdf:about=""> <!-- In case of a well-known Coordinate Reference System an 'Identifier' is enough to describe the CRS --> <crs:CoordinateReferenceSystem svg:transform="rotate(-90) scale(100, 100)"> <crs:Identifier> <crs:code>4326</crs:code> <crs:codeSpace>EPSG</crs:codeSpace> <crs:edition>5.2</crs:edition> </crs:Identifier> </crs:CoordinateReferenceSystem> </rdf:Description> </rdf:RDF> </metadata> <!-- The actual map content --> </svg>
The third example defines the coordinate system completely within the SVG document.
<?xml version="1.0"?> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100" height="100" viewBox="0 0 1000 1000"> <desc>Coordinate metadata defined within the SVG document</desc> <metadata> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:crs="http://www.ogc.org/crs" xmlns:svg="http://www.w3.org/2000/svg"> <rdf:Description rdf:about=""> <!-- For other CRS it should be entirely defined --> <crs:CoordinateReferenceSystem svg:transform="scale(1,-1)"> <crs:NameSet> <crs:name>Mercator projection of WGS84</crs:name> </crs:NameSet> <crs:ProjectedCRS> <!-- The actual definition of the CRS --> <crs:CartesianCoordinateSystem> <crs:dimension>2</crs:dimension> <crs:CoordinateAxis> <crs:axisDirection>north</crs:axisDirection> <crs:AngularUnit> <crs:Identifier> <crs:code>9108</crs:code> <crs:codeSpace>EPSG</crs:codeSpace> <crs:edition>5.2</crs:edition> </crs:Identifier> </crs:AngularUnit> </crs:CoordinateAxis> <crs:CoordinateAxis> <crs:axisDirection>east</crs:axisDirection> <crs:AngularUnit> <crs:Identifier> <crs:code>9108</crs:code> <crs:codeSpace>EPSG</crs:codeSpace> <crs:edition>5.2</crs:edition> </crs:Identifier> </crs:AngularUnit> </crs:CoordinateAxis> </crs:CartesianCoordinateSystem> <crs:CoordinateReferenceSystem> <!-- the reference system of that projected system is WGS84 which is EPSG 4326 in EPSG codeSpace --> <crs:NameSet> <crs:name>WGS 84</crs:name> </crs:NameSet> <crs:Identifier> <crs:code>4326</crs:code> <crs:codeSpace>EPSG</crs:codeSpace> <crs:edition>5.2</crs:edition> </crs:Identifier> </crs:CoordinateReferenceSystem> <crs:CoordinateTransformationDefinition> <crs:sourceDimensions>2</crs:sourceDimensions> <crs:targetDimensions>2</crs:targetDimensions> <crs:ParameterizedTransformation> <crs:TransformationMethod> <!-- the projection is a Mercator projection which is EPSG 9805 in EPSG codeSpace --> <crs:NameSet> <crs:name>Mercator</crs:name> </crs:NameSet> <crs:Identifier> <crs:code>9805</crs:code> <crs:codeSpace>EPSG</crs:codeSpace> <crs:edition>5.2</crs:edition> </crs:Identifier> <crs:description>Mercator (2SP)</crs:description> </crs:TransformationMethod> <crs:Parameter> <crs:NameSet> <crs:name>Latitude of 1st standart parallel</crs:name> </crs:NameSet> <crs:Identifier> <crs:code>8823</crs:code> <crs:codeSpace>EPSG</crs:codeSpace> <crs:edition>5.2</crs:edition> </crs:Identifier> <crs:value>0</crs:value> </crs:Parameter> <crs:Parameter> <crs:NameSet> <crs:name>Longitude of natural origin</crs:name> </crs:NameSet> <crs:Identifier> <crs:code>8802</crs:code> <crs:codeSpace>EPSG</crs:codeSpace> <crs:edition>5.2</crs:edition> </crs:Identifier> <crs:value>0</crs:value> </crs:Parameter> <crs:Parameter> <crs:NameSet> <crs:name>False Easting</crs:name> </crs:NameSet> <crs:Identifier> <crs:code>8806</crs:code> <crs:codeSpace>EPSG</crs:codeSpace> <crs:edition>5.2</crs:edition> </crs:Identifier> <crs:value>0</crs:value> </crs:Parameter> <crs:Parameter> <crs:NameSet> <crs:name>False Northing</crs:name> </crs:NameSet> <crs:Identifier> <crs:code>8807</crs:code> <crs:codeSpace>EPSG</crs:codeSpace> <crs:edition>5.2</crs:edition> </crs:Identifier> <crs:value>0</crs:value> </crs:Parameter> </crs:ParameterizedTransformation> </crs:CoordinateTransformationDefinition> </crs:ProjectedCRS> </crs:CoordinateReferenceSystem> </rdf:Description> </rdf:RDF> </metadata> <!-- the actual map content --> </svg>
Many of the SVG DOM interfaces refer to objects of class SVGPoint. An SVGPoint is an (x, y) coordinate pair. When used in matrix operations, an SVGPoint is treated as a vector of the form:
[x] [y] [1]
If an SVGPoint object is designated as read only, then attempting to assign to one of its attributes will result in an exception being thrown.
[Constructor, Constructor(float x, float y)] interface SVGPoint { attribute float x; attribute float y; SVGPoint matrixTransform(SVGMatrix matrix); };
This interface defines a list of SVGPoint objects.
SVGPointList has the same attributes and methods as other SVGxxxList interfaces. Implementers may consider using a single base class to implement the various SVGxxxList interfaces.
The supported property indices of an SVGPointList object is all non-negative integers less than the length of the list.
interface SVGPointList { readonly attribute unsigned long length; readonly attribute unsigned long numberOfItems; void clear(); SVGPoint initialize(SVGPoint newItem); getter SVGPoint getItem(unsigned long index): SVGPoint insertItemBefore(SVGPoint newItem, unsigned long index); SVGPoint replaceItem(SVGPoint newItem, unsigned long index); SVGPoint removeItem(unsigned long index); SVGPoint appendItem(SVGPoint newItem); setter void (unsigned long index, SVGPoint newItem); };
Many of SVG's graphics operations utilize 2x3 matrices of the form:
[a c e] [b d f]
which, when expanded into a 3x3 matrix for the purposes of matrix arithmetic, become:
[a c e] [b d f] [0 0 1]
[Constructor, Constructor(float a, float b, float c, float d, float e, float f)] interface SVGMatrix { attribute float a; attribute float b; attribute float c; attribute float d; attribute float e; attribute float f; SVGMatrix multiply(SVGMatrix secondMatrix); SVGMatrix inverse(); SVGMatrix translate(float x, float y); SVGMatrix scale(float scaleFactor); SVGMatrix scaleNonUniform(float scaleFactorX, float scaleFactorY); SVGMatrix rotate(float angle); SVGMatrix rotateFromVector(float x, float y); SVGMatrix flipX(); SVGMatrix flipY(); SVGMatrix skewX(float angle); SVGMatrix skewY(float angle); };
SVGTransform is the interface for one of the component
transformations within an SVGTransformList; thus, an
SVGTransform object corresponds to a single component (e.g.,
'scale(…)' or
'matrix(…)') within a ‘transform
’
attribute specification.
[Constructor, Constructor(SVGMatrix matrix), Constructor(DOMString 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; readonly attribute SVGMatrix matrix; readonly attribute float angle; void setMatrix(SVGMatrix 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); };
Creates a new SVGTransform object whose type and matrix attributes are set to values determined by parsing value as a <transform-function>.
If value could not be parsed as a <transform-function>, then a SyntaxError is thrown.
The CSS Transforms specification does not have a grammar for <transform-function> yet.
The matrix that represents this transformation. The matrix object is live, meaning that any changes made to the SVGTransform object are immediately reflected in the matrix object and vice versa. In case the matrix object is changed directly (i.e., without using the methods on the SVGTransform interface itself) then the type of the SVGTransform changes to SVG_TRANSFORM_MATRIX.
A convenience attribute for SVG_TRANSFORM_ROTATE, SVG_TRANSFORM_SKEWX and SVG_TRANSFORM_SKEWY. It holds the angle that was specified.
For SVG_TRANSFORM_MATRIX, SVG_TRANSFORM_TRANSLATE and SVG_TRANSFORM_SCALE, angle will be zero.
Sets the transform type to SVG_TRANSFORM_MATRIX, with parameter matrix defining the new transformation. The values from the parameter matrix are copied, the matrix parameter does not replace SVGTransform::matrix.
This section needs to be updated to describe
how it reflects the value of the ‘transform
’ property,
or just defer to css3-tranforms if everything is defined there.
This interface defines a list of SVGTransform objects.
The SVGTransformList and SVGTransform interfaces correspond
to the various attributes which specify a set of transformations, such as
the ‘transform
’ property which is available for many of SVG's elements.
SVGTransformList has the same attributes and methods as other SVGxxxList interfaces. Implementers may consider using a single base class to implement the various SVGxxxList interfaces.
The supported property indices of an SVGTransformList object is all non-negative integers less than the length of the list.
An SVGTransformList 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.
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); SVGTransform createSVGTransformFromMatrix(SVGMatrix matrix); SVGTransform? consolidate(); setter void (unsigned long index, SVGTransform newItem); };
Creates an SVGTransform object which is initialized to transform of type SVG_TRANSFORM_MATRIX and whose values are the given matrix. The values from the parameter matrix are copied, the matrix parameter is not adopted as SVGTransform::matrix.
transform
’ property which is available for many of
SVG's elements, and which can be animated.
interface SVGAnimatedTransformList { readonly attribute SVGTransformList baseVal; readonly attribute SVGTransformList animVal; };
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.
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; };
interface SVGAnimatedPreserveAspectRatio { readonly attribute SVGPreserveAspectRatio baseVal; readonly attribute SVGPreserveAspectRatio animVal; };
Paths represent the outline of a shape which can be filled, stroked, used as a clipping path, or any combination of the three. (See Filling, Stroking and Paint Servers and Clipping, Masking and Compositing.)
Also they can be used by ‘mpath’ and ‘textPath’.
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), 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 drawing a line to the last moveto) elements. 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.)
Attribute definitions:
SVG 2 Requirement: | Include smooth path between points functionality. |
---|---|
Resolution: | We will add a Catmull Rom syntax to the path syntax with a tension parameter to control the whole curve (not per-point control). |
Purpose: | Provide an easy way to graph data, etc. |
Owner: | Doug (ACTION-3085) |
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) |
A path is defined by including a ‘path’ element which contains a d="(path data)" attribute, where the ‘d’ attribute contains the moveto, line, curve (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>
Path data can contain newline characters and thus can be broken up into multiple lines to improve readability. Because of line length limitations with certain related tools, it is recommended that SVG generators split long path data strings across multiple lines, with each line not exceeding 255 characters. Also note that newline characters are only allowed at certain places within path data.
The path data is defined to allow newline characters, but it should be noted that newlines inside attributes in markup will be normalized to space characters while parsing. If you wanted to, you could write
<path d="M 100,100 L 200,150"/>
but it's not likely that you'd want to.
Are there tools that have line limits nowadays? Do we still need to recommend generators to split up path data at 255 characters?
The sentence about newline characters being allowed only at certain places makes it sound like these places are different from where white space more generally is allowed, but that's not the case.
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.
In the tables below, the following notation is used:
The following sections list the commands.
The "moveto" commands (M or m) establish 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) coordinate. 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. |
The "closepath" (Z or z) ends the current subpath and causes an automatic straight line to be drawn from the current point to the initial point of the current subpath. 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 starts at the same initial point as the current subpath.
When a subpath ends in a "closepath," it differs in behavior
from what happens when "manually" closing a subpath via a
"lineto" command in how ‘stroke-linejoin
’
and ‘stroke-linecap
’ are implemented. With "closepath", the end of the final segment
of the subpath is "joined" with the start of the initial
segment of the subpath using the current value of ‘stroke-linejoin
’.
If you instead "manually" close the subpath via a "lineto"
command, the start of the first segment and the end of the last
segment are not joined but instead are each capped using the
current value of ‘stroke-linecap
’.
At the end of the command, the new current point is set to the
initial point of the current subpath.
Command | Name | Parameters | Description |
---|---|---|---|
Z or z |
closepath | (none) | Close the current subpath by drawing a straight line from the current point to current subpath's initial point. Since the Z and z commands take no parameters, they have an identical effect. |
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 (cpx, cpy) to (x, cpy). 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). At the end of the command, the new current point becomes (x, cpy) for the final value of x. |
V (absolute) v (relative) |
vertical lineto | y+ | Draws a vertical line from the current point (cpx, cpy) to (cpx, y). 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). At the end of the command, the new current point becomes (cpx, y) for the final value of y. |
These three groups of commands draw curves:
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. |
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>
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.
View
this example as SVG (SVG-enabled browsers only)
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. |
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>
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 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. |
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>
The elliptical arc command draws a section of an ellipse which meets 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.
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.
The following notation is used in the Backus-Naur Form (BNF) description of the grammar for path data:
The following is the BNF for SVG paths.
svg-path: wsp* moveto-drawto-command-groups? wsp* moveto-drawto-command-groups: moveto-drawto-command-group | moveto-drawto-command-group wsp* moveto-drawto-command-groups moveto-drawto-command-group: moveto wsp* drawto-commands? drawto-commands: drawto-command | drawto-command wsp* drawto-commands drawto-command: closepath | lineto | horizontal-lineto | vertical-lineto | curveto | smooth-curveto | quadratic-bezier-curveto | smooth-quadratic-bezier-curveto | elliptical-arc moveto: ( "M" | "m" ) wsp* moveto-argument-sequence moveto-argument-sequence: coordinate-pair | coordinate-pair comma-wsp? lineto-argument-sequence closepath: ("Z" | "z") lineto: ( "L" | "l" ) wsp* lineto-argument-sequence lineto-argument-sequence: coordinate-pair | coordinate-pair comma-wsp? lineto-argument-sequence horizontal-lineto: ( "H" | "h" ) wsp* horizontal-lineto-argument-sequence horizontal-lineto-argument-sequence: coordinate | coordinate comma-wsp? horizontal-lineto-argument-sequence vertical-lineto: ( "V" | "v" ) wsp* vertical-lineto-argument-sequence vertical-lineto-argument-sequence: coordinate | coordinate comma-wsp? vertical-lineto-argument-sequence curveto: ( "C" | "c" ) wsp* curveto-argument-sequence curveto-argument-sequence: curveto-argument | curveto-argument comma-wsp? curveto-argument-sequence curveto-argument: coordinate-pair comma-wsp? coordinate-pair comma-wsp? coordinate-pair smooth-curveto: ( "S" | "s" ) wsp* smooth-curveto-argument-sequence smooth-curveto-argument-sequence: smooth-curveto-argument | smooth-curveto-argument comma-wsp? smooth-curveto-argument-sequence smooth-curveto-argument: coordinate-pair comma-wsp? coordinate-pair quadratic-bezier-curveto: ( "Q" | "q" ) wsp* quadratic-bezier-curveto-argument-sequence quadratic-bezier-curveto-argument-sequence: quadratic-bezier-curveto-argument | quadratic-bezier-curveto-argument comma-wsp? quadratic-bezier-curveto-argument-sequence quadratic-bezier-curveto-argument: coordinate-pair comma-wsp? coordinate-pair smooth-quadratic-bezier-curveto: ( "T" | "t" ) wsp* smooth-quadratic-bezier-curveto-argument-sequence smooth-quadratic-bezier-curveto-argument-sequence: coordinate-pair | coordinate-pair comma-wsp? smooth-quadratic-bezier-curveto-argument-sequence elliptical-arc: ( "A" | "a" ) wsp* elliptical-arc-argument-sequence 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 coordinate-pair: coordinate comma-wsp? coordinate coordinate: number nonnegative-number: integer-constant | floating-point-constant number: sign? integer-constant | sign? floating-point-constant flag: "0" | "1" comma-wsp: (wsp+ comma? wsp*) | (comma wsp*) comma: "," integer-constant: digit-sequence floating-point-constant: fractional-constant exponent? | digit-sequence exponent fractional-constant: digit-sequence? "." digit-sequence | digit-sequence "." exponent: ( "e" | "E" ) sign? digit-sequence sign: "+" | "-" digit-sequence: digit | digit digit-sequence digit: "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" wsp: (#x20 | #x9 | #xD | #xA)
The processing of the BNF must consume as much of a given BNF 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 BNF allows the path ‘d’ attribute to be empty. This is not an error, instead it disables rendering of the 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" operation within a ‘path’ element is defined to have zero length. Only the various "lineto", "curveto" and "arcto" commands contribute to path length calculations.
interface SVGPathSeg { // Path Segment Types const unsigned short PATHSEG_UNKNOWN = 0; const unsigned short PATHSEG_CLOSEPATH = 1; const unsigned short PATHSEG_MOVETO_ABS = 2; const unsigned short PATHSEG_MOVETO_REL = 3; const unsigned short PATHSEG_LINETO_ABS = 4; const unsigned short PATHSEG_LINETO_REL = 5; const unsigned short PATHSEG_CURVETO_CUBIC_ABS = 6; const unsigned short PATHSEG_CURVETO_CUBIC_REL = 7; const unsigned short PATHSEG_CURVETO_QUADRATIC_ABS = 8; const unsigned short PATHSEG_CURVETO_QUADRATIC_REL = 9; const unsigned short PATHSEG_ARC_ABS = 10; const unsigned short PATHSEG_ARC_REL = 11; const unsigned short PATHSEG_LINETO_HORIZONTAL_ABS = 12; const unsigned short PATHSEG_LINETO_HORIZONTAL_REL = 13; const unsigned short PATHSEG_LINETO_VERTICAL_ABS = 14; const unsigned short PATHSEG_LINETO_VERTICAL_REL = 15; const unsigned short PATHSEG_CURVETO_CUBIC_SMOOTH_ABS = 16; const unsigned short PATHSEG_CURVETO_CUBIC_SMOOTH_REL = 17; const unsigned short PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS = 18; const unsigned short PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL = 19; readonly attribute unsigned short pathSegType; readonly attribute DOMString pathSegTypeAsLetter; };
interface SVGPathSegClosePath : SVGPathSeg { };
interface SVGPathSegMovetoAbs : SVGPathSeg { attribute float x; attribute float y; };
interface SVGPathSegMovetoRel : SVGPathSeg { attribute float x; attribute float y; };
interface SVGPathSegLinetoAbs : SVGPathSeg { attribute float x; attribute float y; };
interface SVGPathSegLinetoRel : SVGPathSeg { attribute float x; attribute float y; };
interface SVGPathSegCurvetoCubicAbs : SVGPathSeg { attribute float x; attribute float y; attribute float x1; attribute float y1; attribute float x2; attribute float y2; };
interface SVGPathSegCurvetoCubicRel : SVGPathSeg { attribute float x; attribute float y; attribute float x1; attribute float y1; attribute float x2; attribute float y2; };
interface SVGPathSegCurvetoQuadraticAbs : SVGPathSeg { attribute float x; attribute float y; attribute float x1; attribute float y1; };
interface SVGPathSegCurvetoQuadraticRel : SVGPathSeg { attribute float x; attribute float y; attribute float x1; attribute float y1; };
interface SVGPathSegArcAbs : SVGPathSeg { attribute float x; attribute float y; attribute float r1; attribute float r2; attribute float angle; attribute boolean largeArcFlag; attribute boolean sweepFlag; };
interface SVGPathSegArcRel : SVGPathSeg { attribute float x; attribute float y; attribute float r1; attribute float r2; attribute float angle; attribute boolean largeArcFlag; attribute boolean sweepFlag; };