Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What is transform matrix in SVG?

The transform attribute defines a list of transform definitions that are applied to an element and the element's children. Note: As of SVG2, transform is a presentation attribute, meaning it can be used as a CSS property.

Does SVG use Javascript?

Like HTML, SVGs are represented using the Document Object Model (DOM) and so can be manipulated with Javascript relatively easily, especially if you are familiar with using JS with HTML.

What is GetScreenCTM?

GetScreenCTM method. Returns the transformation matrix from current user units (i.e., after application of the 'transform' attribute, if any) to the parent user agent's notice of a “pixel”.

Which css3 transform property is used to rotate SVG objects in html5?

Just use the element type selector and add the transform: rotate(180deg) property to it like in the below snippet.


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

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

// Setting
myElement.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

// Getting
var xforms = myElement.transform.baseVal; // An SVGTransformList
var firstXForm = xforms.getItem(0);       // An SVGTransform
if (firstXForm.type == SVGTransform.SVG_TRANSFORM_TRANSLATE){
  var firstX = firstXForm.matrix.e,
      firstY = firstXForm.matrix.f;
}

// Setting
myElement.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!