3

All:

I wonder how can I get SVG individual transform attribute such as: Translate Scale etcs rather than the whole transform string in D3.

Like in style, I can use style("background-color") to get individual background color rather than the whole style string.

Is there any similar API or method can be applied to transform attribute?

Thanks

Kuan
  • 11,149
  • 23
  • 93
  • 201

2 Answers2

6

You can use d3.transform(), e.g.

var t = d3.transform(element.attr("transform"));
t.translate;
Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
  • Thanks for help, could you give a simple example? – Kuan Feb 13 '15 at 21:18
  • Well what are you looking for? I've put a code sample in my answer. – Lars Kotthoff Feb 13 '15 at 21:21
  • @ Lars Kotthoff Thanks, could you give a simple example how to flip a rectangle by click a button with what you talk about? In a 400 by 400 svg, initially put a rectangle(top:100 left:100) (width:50, height:100). Then click a button, flip it horizontally to (top:100 left:250) based on x=200 flip line – Kuan Feb 13 '15 at 21:30
  • That's a completely different question! On click, set `rectangle.attr("transform", "translate(250,100)")`. – Lars Kotthoff Feb 13 '15 at 21:34
  • Well, actually, it does not have to be a rectangle, it could be any shape, so I can not use simple translate – Kuan Feb 13 '15 at 21:43
  • It sounds like you should ask a separate question about this. You may also find [this question](http://stackoverflow.com/questions/23899718/scale-and-mirror-svg-object) helpful. – Lars Kotthoff Feb 13 '15 at 21:46
  • 1
    For the d3 v4 version, see this other SO post: http://stackoverflow.com/questions/38224875/replacing-d3-transform-in-d3-v4 . Thanks for the right direction @LarsKotthoff of getting the transform like this. –  Dec 08 '16 at 14:56
0

Just change the attributes to move the rectangle where ever you want :)

 var rect = d3.select('rect')
    .attr('x', 400) //move in x direction 
    .attr('y', 200) //move in y direction
    ;

Or transform :

var shape = 'rect' //or any other shape SVG shape you want to select
var x = 200, y= 300; // translate variables

    var rect = d3.select(shape)
    //.attr("transform", "translate(x,y)")
    .attr("transform", "translate(" + x + "," + y + ")");
    ;
AJ_91
  • 581
  • 4
  • 16
  • Thanks, this works as well, I just wonder how to do this in transform – Kuan Feb 18 '15 at 01:22
  • 2
    Thanks, It is kinda the way I want. My problem is how to GET specific attribute of transform rather than SET it, however, this helps as well. – Kuan Feb 18 '15 at 16:42