English 中文(简体)
D3.js - SVG Transformation
  • 时间:2024-12-22

D3.js - SVG Transformation


Previous Page Next Page  

SVG provides options to transform a single SVG shape element or group of SVG elements. SVG transform supports Translate, Scale, Rotate and Skew. Let us learn transformation in this chapter.

Introduction to SVG Transformation

SVG introduces a new attribute, transform to support transformation. The possible values are one or more of the following,

    Translate − It takes two options, tx refers translation along the x-axis and ty refers to the translation along the y-axis. For Example− translate(30 30).

    Rotate − It takes three options, angle refers rotation angle, cx and cy refers to the center of the rotation in the x and y axis. If cx and cy are not specified, then it defaults to the current origin of the coordinate system. For Example − rotate(60).

    Scale − It takes two options, sx refers to the scapng factor along the x-axis and sy refers to the scapng factor along the y-axis. Here, sy is optional and it takes the value of sx, if it is not specified. For Example − scale(10).

    Skew (SkewX and SkewY) − It takes a single option; the skew-angle refers to the angle along the x-axis for SkewX and the angle along the y-axis for SkewY. For Example − skewx(20).

An example of the SVG rectangle with translate, which is described as follows −

<html>
   <head>
      <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
   </head>

   <body>
      <svg width = "300" height = "300">
         <rect x = "20" 
            y = "20"
            width = "60"
            height = "60"
            fill = "green"
            transform = "translate(30 30)">
         </rect>
      </svg>
   </body>
</html>

The above code will yield the following result.