How to manipulate translate transforms on a SVG element with javascript in chrome? How to manipulate translate transforms on a SVG element with javascript in chrome? google-chrome google-chrome

How to manipulate translate transforms on a SVG element with javascript in chrome?


There are two ways to get/set transform values for SVG elements in Chrome, Firefox, IE, or any standards-fearing SVG user agent:

Handling Transforms via Attributes

// Gettingvar xforms = myElement.getAttribute('transform');var parts  = /translate\(\s*([^\s,)]+)[ ,]([^\s,)]+)/.exec(xforms);var firstX = parts[1],    firstY = parts[2];// SettingmyElement.setAttribute('transform','translate(30,100)');

Pros: Simple to set and understand (same as the markup).
Cons: Have to parse the string value to find what you want; for animated values, can't ask for the base value when the animation is active; feels dirty.

Handling Transforms via SVG DOM Bindings

// Gettingvar xforms = myElement.transform.baseVal; // An SVGTransformListvar firstXForm = xforms.getItem(0);       // An SVGTransformif (firstXForm.type == SVGTransform.SVG_TRANSFORM_TRANSLATE){  var firstX = firstXForm.matrix.e,      firstY = firstXForm.matrix.f;}// SettingmyElement.transform.baseVal.getItem(0).setTranslate(30,100);

Pros: No need to try to parse strings on your own; preserves existing transform lists (you can query or tweak just a single transformation in the list); you get real values, not strings.
Cons: Can be confusing to understand at first; more verbose for setting simple values; no convenient method for extracting rotation, scale, or skew values from the SVGTransform.matrix, lack of browser support.

You may find a tool I wrote for exploring the DOM helpful in this.

  1. Go to http://objjob.phrogz.net/svg/object/131
  2. Click the "Show inherited properties/methods?" checkbox
  3. See that the SVGRectElement has a transform property that is an SVGAnimatedTransformList.
  4. Click on SVGAnimatedTransformList to see the properties and methods that object supports.
  5. Explore!


This is a pretty old question, but the answer, in case you were wondering, is that Chrome doesn't like translate(30, 100) - it needs units. It also prefers -webkit-transform for SVG.