6

I was playing with firefox 3.6 and wanted to add a translation to an svg element when clicked; this element already had other translations on it.

var svgs = document.getElementsByTagName("svg:svg");
var group = svgs[0].childNodes[1];
group.addEventListener("click",function(e){
    var group2 = group.cloneNode(true);
    group2.setAttribute("transform", group2.getAttribute("transform")+" translate(10,10)");
    svg2.insertBefore(whole2, whole);
},false);

But another way to do the setAttribute line would be:

group2.translate.baseVal.appendItem(newSVGTransformTranslation);

Where I'm getting stuck is I can call

newSVGTransformTranslation =
  new SVGTransform(SVGTransform.SVG_TRANSFORM_TRANSLATE);

but the resulting object does not have the setTranslate(x,y) method that I expect; nor any setters. Oddly group2.translate.baseVal.getItem(0) does have it, but no clone or copy methods are available.

I must be using the constructor incorrectly. Does anyone have an example of the correct form?

dlamblin
  • 43,965
  • 20
  • 101
  • 140

1 Answers1

14

See SVGSVGElement.createSVGTransform.

An example:

var tfm = svgroot.createSVGTransform();
tfm.setTranslate(x,y);
Erik Dahlström
  • 59,452
  • 12
  • 120
  • 139
  • Thank you, this appears to be the part I was missing. – dlamblin Nov 17 '10 at 21:24
  • 1
    I have been working on this for days, it is really amazing how few examples there are of doing svg transforms with javascript, none of them complete. This answer came closest to a complete answer, and had enough clues that I finally figured out how to do it. – RBarryYoung Apr 14 '20 at 13:28
  • 1
    @RBarryYoung right? I'm so confused to why there is so little documentation or tutorials on svg related transforms and such. Also I know this question is 10 years old but this code is giving me an error in chrome. It says 'createSVGTransform' is not a function. Any ideas? – Chano Apr 15 '21 at 05:31
  • 2
    @Chano Right. Just looked it up in my code, apparently you can *only* get to the `.createSVGTransform` function as a property of the JS object that encapsulates the HTML `...` tags. You cannot get it from any of the SVG objects *within* the svg tag object, only the svg root object. Here's the code I use to get the svg root object from any subordinate svg object: `var svgRoot = svg.viewportElement; //get the element`. Hope this helps! – RBarryYoung Apr 16 '21 at 23:35
  • I think that the only way I was able to figure that out originally was because Erik's code above kindly named the object `svgroot...`. – RBarryYoung Apr 16 '21 at 23:39
  • 1
    @RBarryYoung Yes you are right. It had to be called on the root svg object. I guess I overlooked the naming of the 'svgroot' object above. Thanks!! – Chano Apr 19 '21 at 21:52