Transformations

Get introduced to the transformation functions and their workings on SVG.

Introduction

Transformation is an attribute of SVG that helps in transforming one or more SVG elements. It can take one or more of the following values:

  • Translate
  • Rotate
  • Scale
  • Skew

Let’s explain them one by one through examples.

Translate

Translate is an important functionality in D3.js and is used to move the SVG elements inside the webpage. It takes two values, namely x and y. The x value translates the SVG element along the x-axis, while y translates the SVG element along the y-axis.

Let’s take a dive into the following code to see the transform function in action.

Code for the translate() function.

Explanation

  • The above code from line 1 to line 12 is the same as the previous Drawing a Rectangle lesson.

  • Line 13-14 will be discussed in detail in the next lesson. Currently, it has been used to show the translation visually.

  • Line 15 is where the actual magic happens, where we use the translate(150,150) value of the transform attribute to translate the rectangle 150 pixels along the x-axis and 150 pixels along the y-axis.

Rotate

Let’s explore another important transformation, rotate(). It takes three value cx, cy, and angle. cx and cy are used to define a point about which the rotation will take place. If these values are not specified then default values of cx and cy will be zero (origin).

Let’s apply the rotate transformation to a rectangle to see it in the action.

Code for the rotate() function

In line 15, we have defined the angle of rotation to be 50 by using rotate(50). It can be seen from the output that the rectangle is rotated about the origin by 50 degrees.

Scale

Let’s try to understand another transformation, scale. It is used to upsize or downsize the SVG graphical element and is very helpful in changing the SVG elements’ sizes. If we initialize the scale value to scale(2) for an SVG, then its size will double, and so on.

We can scale graphical elements differently along the x-axis and y-axis by initializing the scale with two values. For example, scale(2,5) will scale up the SVG graphical element by two along the x-axis, and by a factor of five along the y-axis.

Let’s have a look at the example.

Code for the scale() function.

After applying the transform attribute in line 13 with the value scale(2), the radius will now have a value of r=100, cx=200, and cy=200.

Note: The center will also get multiplied by a factor of two.

skewX() and skewY()

Now we are going to discuss the last transformations, skewX and skewY. They each take one value which specifies the angle by which an SVG graphical element will be skewed along the x-axis and y-axis respectively.

Code for the SkewX() function.

Explanation

In the above example, we have skewed the rectangle along the x-axis by an angle of 30 as defined in line 15.