Transforms

From Svg wiki

SVG allows a variety of affine tranformations via the transform matrix. These can affect any rendering element, and can be placed in any container except the <svg> element to affect all child elements. The transform attribute is described in Section 7 of the SVG Spec.

Transforms can be combined in sequence. The syntax is as follows:

<elementName transform='translate(x, y) scale(factor)' />

The order of the commands makes a difference in how it is rendered.

Transforms work not by changing the element's position or geometry, but by manipulating the coordinate system operating on that element.

Contents

Tranformation Commands

Translate

This is the way to change the horizontal and/or vertical position of the target.

translate(x, y)

Rotate

You can rotate the target around any given axis point. The default is the root origin, which is {0,0}, which can be achieved using:

rotate(angle)

In order to specify a different axis of origin, such as the centerpoint of the shape, use the parameters:

rotate(angle, centerX, centerY)

Note that angles are specified in radians, not degrees.

Scale

Scale allows you to change the size and proportions of the target. You can affect either the horizontal dimension, the vetical dimension, or both. If you change them to different values, you will see distortion in the relative proportions of the shape. Scale can be use to increase or decrease the size of the target.

The syntax is as follows:

scale(xFactor, yFactor) 

Scale can also be used to flip a shape, using the syntax:

scale(-1, 1) // horizontal flip
scale(1, -1) // vertical flip

If you provide only the xFactor, that value will be applied to both factors:

scale(0.5) is the same as
scale(0.5, 0.5)

Skew

Skew shifts the given dimension diagonally by a given angle (in radians). The syntax is:

skewX(angle)
skewY(angle)

Matrix

Matrix is a raw command to affect all of the options of the transform matrix, numerically. It is unituitive, but powerful. The syntax is:

matrix(0, 0, 0, 0, 0, 0)

Animation

Each of the tranformations can be affected via declarative SMIL syntax using the <animateTransform> element. An example is as follows:

<animateTransform attributeName='transform' attributeType='XML' type='scale' from='1' to='2' 
begin='0s' dur='4s' fill='freeze' repeatCount='indefinite'/>

Scripting

You can get the current tranformation of an element 2 ways.

You can access explicit attribute values of any given transform using the method getAttributeNS(null, 'translate'). This will require that you parse the values yourself.

You can also get the Current Tranform Matrix, using getCTM(). This looks like the following:

//return list of computed transformation matrix factors, 'a' through 'f',  as integers
var transMatrix = myObject.getCTM();
var factor1 = transMatrix.a;
var factor2 = transMatrix.b;
var factor3 = transMatrix.c;
var factor4 = transMatrix.d;
var factor5 = transMatrix.e;
var factor6 = transMatrix.f;