CSS Transforms

[LONGSTATUS] [DATE]

This version:
http://dev.w3.org/csswg/css3-transforms/
Latest version:
[LATEST]
Previous version:
None
Editors:
Simon Fraser (Apple Inc) <simon.fraser @apple.com>
Dean Jackson (Apple Inc) <dino @apple.com>
David Hyatt (Apple Inc) <hyatt @apple.com>
Chris Marrin (Apple Inc) <cmarrin @apple.com>
Edward O'Connor (Apple Inc) <eoconnor @apple.com>
Dirk Schulze (Adobe Systems, Inc) <dschulze @adobe.com>

Abstract

CSS transforms allows elements styled with CSS to be transformed in two-dimensional or three-dimensional space. This specification is the convergence of the CSS 2D transforms, CSS 3D transforms and SVG transforms specifications.

Status of this document

This specification merges the former CSS 2D Transforms and CSS 3D Transforms specifications and will also merge CSS Transforms and SVG Transforms. The merge is in progress and the specification is not yet ready for review.

The list of changes made to this specification is available.

Table of contents

Introduction

This section is not normative.

The CSS visual formatting model describes a coordinate system within which each element is positioned. Positions and sizes in this coordinate space can be thought of as being expressed in pixels, starting in the upper left corner of the parent with positive values proceeding to the right and down.

This coordinate space can be modified with the 'transform' property. Using transform, elements can be translated, rotated and scaled in two or three dimensional space.

Additional properties make working with transforms easier, and allow the author to control how nested three-dimensional transforms interact.

Note that while some values of the 'transform' property allow an element to be transformed in a three-dimensional coordinate system, the elements themselves are not three-dimensional objects. Instead, they exist on a two-dimensional plane (a flat surface) and have no depth.

There are two roles for transformations in layout: (1) transformations that adjust the position of the affected content without changing the normal layout of that content (much like relative positioning) and (2) transformation of the content prior to layout that affects the layout of that content. See http://lists.w3.org/Archives/Public/www-style/2007Oct/0209 for examples of both cases. The "transform" property (as defined in this document) is equally useful for both roles. This document is focused on satisfying the first role. There is, however, an architectural question that arises because there needs to be a way to distinguish which role an author of a stylesheet wants. The key question is which is the default behavior/role for the "transform" property and how is the other behavior/role indicated by a stylesheet author. If you have an opinion on this topic, please send feedback.
What do fixed backgrounds do in transforms? They should probably ignore the transform completely, since - even transformed - the object should be acting as "porthole" through which the fixed background can be viewed in its original form.

Module Interactions

Write me

CSS Values

Write me

Definitions

When used in this specification, terms have the meanings assigned in this section.

transformable element

A transformable element in the HTML namespace which is either be a block-level or atomic inline-level element, or an element the SVG namespace (see [[SVG11]]) which has the attributes 'transform', 'patternTransform' or 'gradientTransform'.

perpsective matrix

A matrix computed from the values of the perspective and perspective-origin properties as described below.

transformation matrix

A matrix computed from the values of the transform and transform-origin properties as described below.

3D rendering context

A containing block hierarchy of one or more levels, instantiated by elements with a computed value for the transform-style property of preserve-3d, whose elements share a common three-dimensional coordinate system.

The Transform Rendering Model

Specifying a value other than 'none' for the 'transform' property establishes a new local coordinate system at the element that it is applied to. The mapping from where the element would have rendered into that local coordinate system is given by the element's transformation matrix. Transformations are cumulative. That is, elements establish their local coordinate system within the coordinate system of their parent. From the perspective of the user, an element effectively accumulates all the 'transform' properties of its ancestors as well as any local transform applied to it. The accumulation of these transforms defines a current transformation matrix (CTM) for the element.

The coordinate space behaves as described in the coordinate system transformations section of the SVG 1.1 specification. This is a coordinate system with two axes: the X axis increases horizontally to the right; the Y axis increases vertically downwards. Three-dimensional transform functions extent this coordinate space into three dimensions, adding a Z axis perpendicular to the plane of the screen, that increases towards the viewer.

The transformation matrix is computed from the transform and transform-origin properties as follows:

  1. Start with the identity matrix.
  2. Translate by the computed X, Y and Z values of transform-origin
  3. Multiply by each of the transform functions in transform property in turn
  4. Translate by the negated computed X, Y and Z values of transform-origin

Transforms apply to transformable elements.

div {
    transform: translate(100px, 100px);
}

This transform moves the element by 100 pixels in both the X and Y directions.

The 100px translation in X and Y
div {
    height: 100px; width: 100px;
    transform: translate(80px, 80px) scale(1.5, 1.5) rotate(45deg);
}

This transform moves the element by 80 pixels in both the X and Y directions, then scales the element by 150%, then rotates it 45° clockwise about the Z axis. Note that the scale and rotation operate about the center of the element, since the element has the default transform-origin of 50% 50%.

The transform specified above

Note that an identical rendering can be obtained by nesting elements with the equivalent transforms:

<div style="transform: translate(80px, 80px)">
  <div style="transform: scale(1.5, 1.5)">
    <div style="transform: rotate(45deg)"></div>
  </div>
</div>

In the HTML namespace, the transform property does not affect the flow of the content surrounding the transformed element. However, the extent of the overflow area takes into account transformed elements. This behavior is similar to what happens when elements are offset via relative positioning. Therefore, if the value of the 'overflow' property is 'scroll' or 'auto', scrollbars will appear as needed to see content that is transformed outside the visible area.

In the HTML namespace, any value other than 'none' for the transform results in the creation of both a stacking context and a containing block. The object acts as a containing block for fixed positioned descendants.

Is this affect on position:fixed necessary? If so, need to go into more detail here about why fixed positioned objects should do this, i.e., that it's much harder to implement otherwise.

3D Transform Rendering

Normally, elements render as flat planes, and are rendered into the same plane as their containing block. Often this is the plane shared by the rest of the page. Two-dimensional transform functions can alter the appearance of an element, but that element is still rendered into the same plane as its containing block.

Three-dimensional transforms can result in transformation matrices with a non-zero Z component, potentially lifting them off the plane of their containing block. Because of this, elements with three-dimensional transformations could potentially render in an front-to-back order that different from the normal CSS rendering order, and intersect with each other. Whether they do so depends on whether the element is a member of a 3D rendering context, as described below.

This description does not exactly match what WebKit implements. Perhaps it should be changed to match current implementations?

This example shows the effect of three-dimensional transform applied to an element.

<style>
div { height: 150px; width: 150px; }
.container { border: 1px solid black; }
.transformed { transform: rotateY(50deg); }
</style>

<div class="container">
    <div class="transformed"></div>
</div>
Div with a rotateY transform.

The transform is a 50° rotation about the vertical, Y axis. Note how this makes the blue box appear narrower, but not three-dimensional.

The perspective and perspective-origin properties can be used to add a feeling of depth to a scene by making elements higher on the Z axis (closer to the viewer) appear larger, and those futher away to appear smaller.

The perspective matrix is computed as follows:

  1. Start with the identity matrix.
  2. Translate by the computed X and Y values of perspective-origin
  3. Multiply by the matrix that would be obtained from the perspective(<length>) transform function, where the length is provided by the value of the perspective property
  4. Translate by the negated computed X and Y values of perspective-origin

This example shows how perspective can be used to cause three-dimensional transforms to appear more realistic.

<style>
div { height: 150px; width: 150px; }
.container { perspective: 500px; border: 1px solid black; }
.transformed { transform: rotateY(50deg); }
</style>

<div class="container">
    <div class="transformed"></div>
</div>
Div with a rotateY transform,
                    and perspective on its container

The inner element has the same transform as in the previous example, but its rendering is now influenced by the perspective property on its parent element. Perspective causes vertices that have positive Z coordinates (closer to the viewer) to be scaled up in X and Y, and those futher away (negative Z coordinates) to be scaled down, giving an appearance of depth.

An element with a three-dimensional transform that is not contained in a 3D rendering context renders with the appropriate transform applied, but does not intersect with any other elements. The three-dimensional transform in this case can be considered just as a painting effect, like two-dimensional transforms. Similarly, the transform does not affect painting order. For example, a transform with a positive Z translation may make an element look larger, but does not cause that element to render in front of elements with no translation in Z.

An element with a three-dimensional transform that is contained in a 3D rendering context can visibly interact with other elements in that same 3D rendering context; the set of elements participating in the same 3D rendering context may obscure each other or intersect, based on their computed transforms. They are rendered as if they are all siblings, positioned in a common 3D coordinate space. The position of each element in that three-dimensional space is determined by accumulating the transformation matrices up from the element that establishes the 3D rendering context through each element that is a containing block for the given element, as described below.

<style>
div { height: 150px; width: 150px; }
.container { perspective: 500px; border: 1px solid black; }
.transformed { transform: rotateY(50deg); background-color: blue; }
.child { transform-origin: top left; transform: rotateX(40deg); background-color: lime; }
</style>

<div class="container">
  <div class="transformed">
    <div class="child"></div>
  </div>
</div>

This exmaple shows how nested 3D transforms are rendered in the absence of transform-style: preserve-3d. The blue div is transformed as in the previous example, with its rendering influenced by the perspective on its parent element. The lime element also has a 3D transform, which is a rotation about the X axis (anchored at the top, by virtue of the transform-origin). However, the lime element is being rendered into the plane of its parent because it is not a member of a 3D rendering context; the parent is "flattening".

Nested 3D transforms, with flattening

Elements establish and participate in 3D rendering contexts as follows:

The final value of the transform used to render an element in a 3D rendering context is computed by accumulating a matrix as follows:

  1. Start with the identity matrix
  2. For each containing block between the root of the 3D rendering context and the element in question:
    1. multiply the accumulated matrix with the perspective matrix on the element's containing block (if any). That contining block is not necessarily a member of the 3D rendering context.
    2. apply to the accumulated matrix a translation equivalent to the horizontal and vertical offset of the element relative to its containing block as specified by the CSS visual formatting model.
    3. multiply the accumulated matrix with the transformation matrix.
<style>
div { height: 150px; width: 150px; }
.container { perspective: 500px; border: 1px solid black; }
.transformed { transform-style: preserve-3d; transform: rotateY(50deg); background-color: blue; }
.child { transform-origin: top left; transform: rotateX(40deg); background-color: lime; }
</style>

This example is identical to the previous example, with the addition of transform-style: preserve-3d on the blue element. The blue element now establishes a 3D rendering context, of which the lime element is a member. Now both blue and lime elements share a common three-dimensional space, so the lime element renders as tilting out from its parent, influenced by the perspective on the container.

Nested 3D transforms, with preserve-3d.

Should intersection behavior be normative?

Elements in the same 3D rendering context may intersect with eachother. User agents should subdivide the planes of intersecting elements as described by Newell's algorithm to render intersection.

Untransformed elements in a 3D rendering context render on the Z=0 plane, yet may still intersect with transformed elements.

Within a 3D rendering context, the rendering order of non-intersecting elements is based on their position on the Z axis after the application of the accumulated transform. Elements at the same Z position render in stacking context order.

<style>
.container {
    background-color: rgba(0, 0, 0, 0.3);
    transform-style: preserve-3d;
    perspective: 500px;
}
.container > div {
    position: absolute;
    left: 0;
}
.container > :first-child {
    transform: rotateY(45deg);
    background-color: orange;
    top: 10px;
    height: 135px;
}
.container > :last-child {
    transform: translateZ(40px);
    background-color: rgba(0, 0, 255, 0.75);
    top: 50px;
    height: 100px;
}
</style>

<div class="container">
    <div></div>
    <div></div>
</div>

This example shows show elements in a 3D rendering context can intersect. The container element establishes a 3D rendering context for itself and its two children. The children intersect with eachother, and the orange element also intersects with the container.

Intersecting sibling elements.

Using three-dimensional transforms, it's possible to transform an element such that its reverse side is towards the viewer. 3D-tranformed elements show the same content on both sides, so the reverse side looks like a mirror-image of the front side (as if the element were painted onto a sheet of glass). Normally, elements whose reverse side is towards the viewer remain visible. However, the 'backface-visibility' property allows the author to make an element invisible when its reverse side is towards the viewer. This behavior is "live"; if an element with backface-visibility: hidden were animating, such that its front and reverse sides were alternately visible, then it would only be visible when the front side were towards the viewer.

The 'transform' Property

A transformation is applied to the coordinate system an element renders in through the 'transform' property. This property contains a list of transform functions. The final transformation value for a coordinate system is obtained by converting each function in the list to its corresponding matrix (either defined in this specification or by reference to the SVG specification), then multiplying the matrices.

Name: transform
Value: none | <transform-function> [ <transform-function> ]*
Initial: none
Applies to: transformable elements
Inherited: no
Percentages: refer to the size of the element's border box
Media: visual
Computed value: See below.

We need to resolve whether the computed value is the same as the specified value, or matrix().

The computed value of the transform property is a matrix() or matrix3d() value that describes the matrix that results from concatenating the individual transform functions. If the resulting matrix can be represented as a two-dimensional matrix with no loss of information, then a matrix() value is returned, otherwise a matrix3d() value. For elements with no transform applied, the computed value is 'none'.

Any value other than 'none' for the transform results in the creation of both a stacking context and a containing block. The object acts as a containing block for fixed positioned descendants.

The SVG transform attribute

The SVG 1.1 specification did not specify the 'transform' attribute as a presentation attribute. In order to improve the integration of SVG and HTML, this specification makes the SVG 'transform' attribute a 'presentation attribute' and makes the 'transform' property one that applies to SVG elements.

SVG transform attribute specificity

Since the SVG attribute becomes a presentation attribute, its participation to the CSS cascade is determined by the specificity of presentation attributes, as explained in the SVG specification.

SVG transform attribute DOM

The SVG specification defines a DOM interface to access the animated and base value of the SVG transform attribute. To ensure backwards compatibility, this API should still be supported by user agents. The baseVal should be the value of the 'transform' attribute, as set on the element, and the animVal should be the property's computed value which account for CSS animation, if any is underway.

The 'transform-origin' Property

Name: transform-origin
Value: [ top | bottom ] |
[ <percentage> | <length> | left | center | right ] [ <percentage> | <length> | top | center | bottom ]? |
[ center | [ left | right ] [ <percentage> | <length> ]? ] && [ center | [ top | bottom ] [ <percentage> | <length> ]? ]
Initial: 0 0 for SVG elements, 50% 50% for all other elements
Applies to: transformable elements
Inherited: no
Percentages: refer to the size of the element's border box
Media: visual
Computed value: For <length> the absolute value, otherwise a percentage

The values of the 'transform' and 'transform-origin' properties are used to compute the transformation matrix, as described above.

If only one value is specified, the second value is assumed to be 'center'. If two values are given and at least one value is not a keyword, then the first value represents the horizontal position (or offset) and the second represents the vertical position (or offset). <percentage> and <length> values here represent an offset of the transform origin from the top left corner of the element's border box.

If three or four values are given, then each <percentage> or<length> represents an offset and must be preceded by a keyword, which specifies from which edge the offset is given. For example, ''transform-origin: bottom 10px right 20px'' represents a ''10px'' vertical offset up from the bottom edge and a ''20px'' horizontal offset leftward from the right edge. If three values are given, the missing offset is assumed to be zero.

Positive values represent an offset inward from the edge of the border box. Negative values represent an offset outward from the edge of the border box.

The 'transform-origin' property for SVG elements

Should we use 'auto', or explicitly say that transform-origin is 0 0 for SVG elements, 50% 50% for all other elements (bug 15504)?

To keep the 'transform' property compatible with existing SVG content that assumed a top/left coordinate system origin, the user agent stylesheet must contain the following:

svg | * {
    transform-origin: top left;
}                  
              

Need to add 3D transform-origin variant in a way that is not ambiguous with the background-origin syntax (bug 15432).

The 'transform-style' Property

Name: transform-style
Value: flat | preserve-3d
Initial: flat
Applies to: transformable elements
Inherited: no
Percentages: N/A
Media: visual
Computed value: Same as specified value.

A value of preserve-3d for transform-style establishes a stacking context.

The following CSS property values require the user agent to create a flattened representation of the descendant elements before they can be applied, and therefore override the behavior of transform-style: preserve-3d:

Should this affect the computed value of transform-style?

The values of the 'transform' and 'transform-origin' properties are used to compute the transformation matrix, as described above.

The 'perspective' Property

Name: perspective
Value: none | <length>
Initial: none
Applies to: transformable elements
Inherited: no
Percentages: N/A
Media: visual
Computed value: Same as specified value.

If the value is 'none', less than or equal to 0 no perspective transform is applied.

The use of this property with any value other than 'none' establishes a stacking context. It also establishes a containing block (somewhat similar to position:relative), just like the 'transform' property does.

The values of the perspective and perspective-origin properties are used to compute the perspective matrix, as described above.

The 'perspective-origin' Property

The 'perspective-origin' property establishes the origin for the perspective property. It effectively sets the X and Y position at which the viewer appears to be looking at the children of the element.

Name: perspective-origin
Value: [ [ <percentage> | <length> | left | center | right ] [ <percentage> | <length> | top | center | bottom ]? ] | [ [ left | center | right ] || [ top | center | bottom ] ]
Initial: 50% 50%
Applies to: transformable elements
Inherited: no
Percentages: refer to the size of the element's border box
Media: visual
Computed value: Same as specified value.

The values of the perspective and perspective-origin properties are used to compute the perspective matrix, as described above.

The 'backface-visibility' Property

The 'backface-visibility' property determines whether or not the "back" side of a transformed element is visible when facing the viewer. With an identity transform, the front side of an element faces the viewer. Applying a rotation about Y of 180 degrees (for instance) would cause the back side of the element to face the viewer.

This property is useful when you place two elements back-to-back, as you would to create a playing card. Without this property, the front and back elements could switch places at times during an animation to flip the card. Another example is creating a box out of 6 elements, but where you want to see the inside faces of the box. This is useful when creating the backdrop for a 3 dimensional stage.

Name: backface-visibility
Value: visible | hidden
Initial: visible
Applies to: transformable elements
Inherited: no
Percentages: N/A
Media: visual
Computed value: Same as specified value.

The visibility of an element with backface-visibility: hidden is determined as follows:

  1. Compute a matrix representing the accumulated transform from the viewport, taking the translations due to the CSS visual formatting mode, the perpsective and transformation matrices into account, in a similar manner to the computation of the accumulated transform for an element in a 3D rendering context.
  2. If the component of the matrix in row 3, column 3 is negative, then the element should be hidden, otherwise it is visible.
Is the relevant matrix here really relative to the viewport, or to the root of the 3D rendering context?

The Transformation Functions

The value of the transform property is a list of <transform-functions> applied in the order provided. The individual transform functions are separated by whitespace. The set of allowed transform functions is given below. In this list the type <translation-value> is defined as a <length> or <percentage> value, and the <angle> type is defined by CSS Values and Units. Wherever <angle> is used in this specification, a <number> that is equal to zero is also allowed, which is treated the same as an angle of zero degrees.

2D Transformation Functions

matrix(<number>, <number>, <number>, <number>, <number>, <number>)
specifies a 2D transformation in the form of a transformation matrix of six values. matrix(a,b,c,d,e,f) is equivalent to applying the transformation matrix [a b c d e f].
translate(<translation-value>[, <translation-value>])
specifies a 2D translation by the vector [tx, ty], where tx is the first translation-value parameter and ty is the optional second translation-value parameter. If <ty> is not provided, ty has zero as a value.
translateX(<translation-value>)
specifies a translation by the given amount in the X direction.
translateY(<translation-value>)
specifies a translation by the given amount in the Y direction.
scale(<number>[, <number>])
specifies a 2D scale operation by the [sx,sy] scaling vector described by the 2 parameters. If the second parameter is not provided, it is takes a value equal to the first. For example, scale(1, 1) would leave an element unchanged, while scale(2, 2) would cause it to appear twice as long in both the X and Y axes, or four times its typical geometric size.
scaleX(<number>)
specifies a scale operation using the [sx,1] scaling vector, where sx is given as the parameter.
scaleY(<number>)
specifies a scale operation using the [1,sy] scaling vector, where sy is given as the parameter.
rotate(<angle>)
specifies a 2D rotation by the angle specified in the parameter about the origin of the element, as defined by the transform-origin property. For example, rotate(90deg) would cause elements to appear rotated one-quarter of a turn in the clockwise direction.
skew(<x-angle>[, <y-angle>])
specifies a skew in X and Y. If <y-angle> is not provided, it is has a zero value. The resulting transformation matrix is [1, tan(y-angle), tan(x-angle), 1, 0, 0].
skewX(<angle>)
specifies a skew transformation along the X axis by the given angle.
skewY(<angle>)
specifies a skew transformation along the Y axis by the given angle.

3D Transformation Functions

matrix3d(<number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>)
specifies a 3D transformation as a 4x4 homogeneous matrix of 16 values in column-major order.
translate3d(<translation-value>, <translation-value>, <translation-value>)
specifies a 3D translation by the vector [tx,ty,tz], with tx, ty and tz being the first, second and third translation-value parameters respectively. <Percentage> values are not allowed in the tz translation-value, and if present will cause the propery value to be invalid.
translateZ(<translation-value>)
specifies a translation by the given amount in the Z direction. <Percentage> values are not allowed in the translateZ translation-value, and if present will cause the propery value to be invalid.
scale3d(<number>, <number>, <number>)
specifies a 3D scale operation by the [sx,sy,sz] scaling vector described by the 3 parameters.
scaleZ(<number>)
specifies a scale operation using the [1,1,sz] scaling vector, where sz is given as the parameter.
rotate3d(<number>, <number>, <number>, <angle>)
Clarify "clockwise". Describe in terms of right-hand rule?
specifies a clockwise 3D rotation by the angle specified in last parameter about the [x,y,z] direction vector described by the first 3 parameters. If the direction vector is not of unit length, it will be normalized. A direction vector that cannot be normalized, such as [0, 0, 0], will cause the rotation to not be applied. This function is equivalent to matrix3d(1 + (1-cos(angle))*(x*x-1), -z*sin(angle)+(1-cos(angle))*x*y, y*sin(angle)+(1-cos(angle))*x*z, 0, z*sin(angle)+(1-cos(angle))*x*y, 1 + (1-cos(angle))*(y*y-1), -x*sin(angle)+(1-cos(angle))*y*z, 0, -y*sin(angle)+(1-cos(angle))*x*z, x*sin(angle)+(1-cos(angle))*y*z, 1 + (1-cos(angle))*(z*z-1), 0, 0, 0, 0, 1).
rotateX(<angle>)
specifies a clockwise rotation by the given angle about the X axis.
rotateY(<angle>)
specifies a clockwise rotation by the given angle about the Y axis.
rotateZ(<angle>)
specifies a clockwise rotation by the given angle about the Z axis. This is a synonym for rotate(<angle>).
perspective(<length>)
specifies a perspective projection matrix. This matrix scales points in X and Y based on their Z value, scaling points with positive Z values away from the origin, and those with negative Z values towards the origin. Points on the z=0 plane are unchanged. The depth, given as the parameter to the function, represents the distance of the z=0 plane from the viewer. Lower values give a more flattened pyramid and therefore a more pronounced perspective effect. For example, a value of 1000px gives a moderate amount of foreshortening and a value of 200px gives an extreme amount. The matrix is computed by starting with an identity matrix and replacing the value at row 3, column 4 with the value -1/depth. The value for depth must be greater than zero, otherwise the function is invalid.

Transform Values and Lists

The <translation-value> values are defined as [<percentage> | <length>]. All other value types are described as CSS types. If a list of transforms is provided, then the net effect is as if each transform had been specified separately in the order provided. For example,

<div style="transform:translate(-10px,-20px) scale(2) rotate(45deg) translate(5px,10px)"/>

is functionally equivalent to:

<div style="transform:translate(-10px,-20px)">
  <div style="transform:scale(2)">
    <div style="transform:rotate(45deg)">
      <div style="transform:translate(5px,10px)">
      </div>
    </div>
  </div>
</div>

That is, in the absence of other styling that affects position and dimensions, a nested set of transforms is equivalent to a single list of transform functions, applied from the outside in. The resulting transform is the matrix multiplication of the list of transforms.

Transitions and animations between transform values

When animating or transitioning the value of a transform property the rules described below are applied. The 'from' transform is the transform at the start of the transition or current keyframe. The 'end' transform is the transform at the end of the transition or current keyframe.

In some cases, an animation might cause a transformation matrix to be singular or non-invertible. For example, an animation in which scale moves from 1 to -1. At the time when the matrix is in such a state, the transformed element is not rendered.

Matrix decomposition for animation

When interpolating between 2 matrices, each is decomposed into the corresponding translation, rotation, scale and skew values. Not all matrices can be accurately described by these values. Those that can't are decomposed into the most accurate representation possible, using the technique below. This technique is taken from The "unmatrix" method in "Graphics Gems II, edited by Jim Arvo", simplified for the 2D case.

Unmatrix

          Input:  a, b, c, d ; 2x2 matrix (rotate, scale, shear) components
                  tx, ty     ; translation components
          Output: translate  ; a 2 component vector
                  rotate     ; an angle
                  scale      ; a 2 component vector
                  skew       ; skew factor
          Returns false if the matrix cannot be decomposed, true if it can

          Supporting functions (point is a 2 component vector):
            float  length(point)                returns the length of the passed vector
            point  normalize(point)             normalizes the length of the passed point to 1
            float  dot(point, point)            returns the dot product of the passed points
            float  atan2(float y, float x)      returns the principal value of the arc tangent of 
                                                y/x, using the signs of both arguments to determine 
                                                the quadrant of the return value

          Decomposition also makes use of the following function:
            point combine(point a, point b, float ascl, float bscl)
                result[0] = (ascl * a[0]) + (bscl * b[0])
                result[1] = (ascl * a[1]) + (bscl * b[1])
                return result

          // Make sure the matrix is invertible
          if ((a * d - b * c) == 0)
            return false

          // Take care of translation
          translate[0] = tx
          translate[1] = matrix[3][1]

          // Put the components into a 2x2 matrix 'mat'
          mat[0][0] = a
          mat[0][1] = b
          mat[1][0] = c
          mat[1][1] = d

          // Compute X scale factor and normalize first row.
          scale[0] = length(row[0])
          row[0] = normalize(row[0])

          // Compute shear factor and make 2nd row orthogonal to 1st.
          skew = dot(row[0], row[1])
          row[1] = combine(row[1], row[0], 1.0, -skew)

          // Now, compute Y scale and normalize 2nd row.
          scale[1] = length(row[1])
          row[1] = normalize(row[1])
          skew /= scale[1];

          // Now, get the rotation out
          rotate = atan2(mat[0][1], mat[0][0])

          return true;

Animating the components

Once decomposed, each component of each returned value of the source matrix is linearly interpolated with the corresponding component of the destination matrix. For instance, the translate[0] and translate[1] values are interpolated numerically, and the result is used to set the translation of the animating element.

Recomposing the matrix

This section is not normative.

After interpolation the resulting values are used to position the element. One way to use these values is to recompose them into a 3x2 matrix. This can be done using the Transformation Functions of the transform property. The following JavaScript example produces a string for this purpose. The values passed in are the output of the Unmatrix function above:

        function compose(translate, rotate, scale, skew, elementID)
        {
            var s = " translate(" + translate[0] + ", " + translate[1] + ")";
            s += " rotate(" + rotate + ")";
            s += " skewX(" + skew + ")";
            s += " scale(" + scale[0] + ", " + scale[1] + ")";
            document.getElementById(elementID).style.transform = s;
        }

DOM Interfaces

This section describes the interfaces and functionality added to the DOM to support runtime access to the functionality described above.

CSSMatrix

We actually describe a 3x2 matrix here, similar to SVGMatrix.

We need to resolve how SVGMatrix and CSSMatrix work together (bug 15498).

Interface CSSMatrix

The CSSMatrix interface represents a 3x2 homogeneous matrix.

IDL Definition
          interface CSSMatrix {
              attribute float a;
              attribute float b;
              attribute float c;
              attribute float d;
              attribute float e;
              attribute float f;

              void        setMatrixValue(in DOMString string) raises(DOMException);
              CSSMatrix   multiply(in CSSMatrix secondMatrix);
              CSSMatrix   inverse() raises(DOMException);
              CSSMatrix   translate(in float x, in float y);
              CSSMatrix   scale(in float scaleX, in float scaleY);
              CSSMatrix   skewX(in float angle);
              CSSMatrix   skewY(in float angle);
              CSSMatrix   rotate(in float angle);
          };

Attributes
a-f of type float
Each of these attributes represents one of the values in the 3x2 matrix.
Methods
setMatrixValue
The setMatrixValue method replaces the existing matrix with one computed from parsing the passed string as though it had been assigned to the transform property in a CSS style rule.
Parameters
string of type DOMString
The string to parse.
No Return Value
Exceptions
DOMException SYNTAX_ERR
Thrown when the provided string can not be parsed into a CSSMatrix.
multiply
The multiply method returns a new CSSMatrix which is the result of this matrix multiplied by the passed matrix, with the passed matrix to the right. This matrix is not modified.
Parameters
secondMatrix of type CSSMatrix
The matrix to multiply.
Return Value
CSSMatrix
The result matrix.
No Exceptions
inverse
The inverse method returns a new matrix which is the inverse of this matrix. This matrix is not modified.
No Parameters
Return Value
CSSMatrix
The inverted matrix.
Exceptions
DOMException NOT_SUPPORTED_ERR
Thrown when the CSSMatrix can not be inverted.
translate
The translate method returns a new matrix which is this matrix multiplied by a translation matrix containing the passed values. This matrix is not modified.
Parameters
x of type float
The X component of the translation value.
y of type float
The Y component of the translation value.
Return Value
CSSMatrix
The result matrix.
No Exceptions
scale
The scale method returns a new matrix which is this matrix multiplied by a scale matrix containing the passed values. If the y component is undefined, the x component value is used in its place. This matrix is not modified.
Parameters
scaleX of type float
The X component of the scale value.
scaleY of type float
The (optional) Y component of the scale value.
Return Value
CSSMatrix
The result matrix.
No Exceptions
rotate
The rotate method returns a new matrix which is this matrix multiplied by a rotation matrix. The rotation value is in degrees. This matrix is not modified.
Parameters
angle of type float
The angle of rotation.
Return Value
CSSMatrix
The result matrix.
No Exceptions
skewX
The skewX method returns a new matrix which is this matrix multiplied by a matrix representing a skew along the x-axis. The rotation value is in degrees. This matrix is not modified.
Parameters
angle of type float
The angle of skew along the X axis.
Return Value
CSSMatrix
The result matrix.
No Exceptions
skewY
The skewX method returns a new matrix which is this matrix multiplied by a matrix representing a skew along the y-axis. The rotation value is in degrees. This matrix is not modified.
Parameters
angle of type float
The angle of skew along the Y axis.
Return Value
CSSMatrix
The result matrix.
No Exceptions

References

Normative references

Other references

Property index

Index