SVG Scripting Reading/Writing Attributes


Example

You can use either DOM Level 2 Core methods getAttribute(), getAttributeNS(), setAttribute(), and setAttributeNS() to read and write values from SVG elements, or you can use custom properties and methods specified in the SVG 1.1 IDL (Interface Definition Language).

Simple Numeric Attributes

For example, if you have an SVG circle element:

<circle id="circ" cx="10" cy="20" r="15" />

you can either use DOM methods to read and write the attributes:

var circ = document.querySelector('#circ');
var x = circ.getAttribute('cx') * 1; // Use *1 to convert from string to number value
circ.setAttribute('cy', 25);

...or you can use the custom cx, cy, and r properties defined for SVGCircleElement. Note that these are not direct numbers, but instead—as with many accessors in SVG 1.1—they allow for access to animated values. These properties are of type SVGAnimatedLength. Disregarding animation and length units, you can use such attributes like:

var x = circ.cx.baseVal.value; // this is a number, not a string
circ.cy.baseVal.value = 25;

Transformations

SVG groups may be used to move, rotate, scale, and otherwise transform multiple graphical elements as a whole. (For details on SVG translations, see Chapter 7). Here is a group that makes a smiley face that you can adjust the size, rotation, and placement of by adjusting the transform:

<g id="smiley" transform="translate(120,120) scale(5) rotate(30)">
  <circle r="20" fill="yellow" stroke-width="2"/>
  <path fill="none" d="M-10,5 a 5 3 0 0 0 20,0" stroke-width="2"/>
  <circle cx="-6" cy="-5" r="2" fill="#000"/>
  <circle cx="6"  cy="-5" r="2" fill="#000"/>
</g>

Using script to adjust the scale of this via DOM methods requires manipulating the entire transform attribute as a string:

var face = document.querySelector('#smiley');

// Find the full string value of the attribute
var xform = face.getAttribute('transform');

// Use a Regular Expression to replace the existing scale with 'scale(3)'
xform = xform.replace( /scale\s*\([^)]+\)/, 'scale(3)' );

// Set the attribute to the new string.
face.setAttribute('transform',xform);

With the SVG DOM one can traverse the specific transforms in the list, find the desired one, and modify the values:

var face = document.querySelector('#smiley');

// Get the SVGTransformList, ignoring animation
var xforms = face.transform.baseVal;          

// Find the scale transform (pretending we don't know its index)
for (var i=0; i<xforms.numberOfItems; ++i){
  // Get this part as an SVGTransform
  var xform = xforms.getItem(i);
  if (xform.type == SVGTransform.SVG_TRANSFORM_SCALE){
    // Set the scale; both X and Y scales are required
    xform.setScale(3,3);
    break;
  }
}