Home > Enterprise >  D3.js How to get value of transform attr
D3.js How to get value of transform attr

Time:01-28

I have a small question. In my application I'm using d3.js. And I need to get the values of transform attribute. I found the same question How to log rotate attribute in transform using d3.js? But I am using a newer version of the library. How can I get it? Because:

<g class='myclass' transform='translate(30, 0)'>

...

d3.select('.myclass').attr('transform')

return the string.

translate(30, 0)

(I need to get only numbers 30 and 0)I didn't find any functions for this. I can get values using regex, but I think it too much in this case. There must be some normal way to get these values. Thanks!

CodePudding user response:

Since the <g> element implements the SVGGraphicsElement interface it features a .transform property that allows access to the SVGAnimatedTransformList containing the transformations on that element. Given that there is only one translation like in your code it can be accessed like this:

d3.select("g").node()
  .transform          // get the animated transform list
  .baseVal            // get its base value
  .getItem(0)         // get the first transformation from the list, i.e. your translate
  .matrix             // get the matrix containing the values

The .matrix property is of type SVGMatrix and contains the values for the translation of the group element in its e and f properties.

Have a look at the following demo to see it in action:

const translate = d3.select("g").node() // get the node
                    .transform          // get the animated transform list
                    .baseVal            // get its base value
                    .getItem(0)         // get the first transformation from the list, i.e. your translate
                    .matrix             // get the matrix containing the values
                    
console.log(`Translate x: ${translate.e}, y: ${translate.f}`);
<script src="https://d3js.org/d3.v7.js"></script>
<svg>
  <g transform='translate(30, 0)'></g>
</svg>

  •  Tags:  
  • Related