trojal.

(adventures in web programming.)

Recent Entries
Categories
Meta (2)
Test (3)
Random (1)
jQuery (1)
SVG (1)
Links
Info
Edit

SVG Interactions

-trojal @ 2010-Jan-27 01:08 UTC

Step 3: Adding translation

(link)

The Interaction

Ctrl + drag to translate the image.

The JavaScript

Rewrote the graphics scaling and translation to use computed matrix transformations in SVG instead of using the built-in scale and translate attributes in SVG. To transform the [likely already transformed] image with a transformation, one needs to multiply the transformation matrices. But, as David Jones points out on his blog (and whose code snippet I use), "The trouble with matrix multiplication is that it's not commutative."

function translate(e){
  var posx = 0;
  var posy = 0;
  if (!e) var e = window.event;
  if (e.pageX || e.pageY) {
    posx = e.pageX;
    posy = e.pageY;
  } else if (e.clientX || e.clientY) {
    posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
    posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
  }
  var g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
  g.setAttribute('transform', 'translate(' + (posx - vars.posx) + ' ' + (posy - vars.posy) + ')');
  document.getElementById('base').transform.baseVal.replaceItem(matmul(g.transform.baseVal.getItem(0).matrix, document.getElementById('base').transform.baseVal.getItem(0).matrix), 0);
  document.getElementById('root').setAttribute('width', parseFloat(document.getElementById('root').getAttribute('width'))+posx-vars.posx);
  document.getElementById('root').setAttribute('height', parseFloat(document.getElementById('root').getAttribute('height'))+posy-vars.posy);
  this.onmouseup = null;
  vars.posx = null;
  vars.posy = null;
  return false;
}

Next up: Step 4: Live translation, rotation, and 3D