Search code examples
jqueryanimationsvgzoomingraphael

Raphael paper zoom animation


I managed to do some hack in order to zoom raphael paper, as setviewbox wasn't working for me, here is the function I wrote:

function setCTM(element, matrix) {
    var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";

    element.setAttribute("transform", s);
}

Raphael.fn.zoomAndMove = function(coordx,coordy,zoom) {

    var svg = document.getElementsByTagName("svg")[0];

    var z = zoom;

    var g = document.getElementById("viewport1");
    var p = svg.createSVGPoint();

    p.x = coordx; 
    p.y = coordy;

    p = p.matrixTransform(g.getCTM().inverse());

    var k = svg.createSVGMatrix().scale(z).translate(-p.x, -p.y);
    setCTM(g, g.getCTM().multiply(k));
} 

where the viewport1 element was defined as :

var gelem = document.createElementNS('http://www.w3.org/2000/svg', 'g');
gelem.id = 'viewport1';

paper.canvas.appendChild(gelem);
paper.canvas = gelem;

Then I can call: paper.zoomAndMove(minx,miny,zoomRatio);

Is it possible to transform the function to make it zoom smoothly?


Solution

  • See this JS Fiddle example for utilizing jQuery and Raphael's setViewBox which does both zooming and panning smoothly. We use the exact same functionality in a much more complicated and larger context and it works perfect and remains smooth even with a large number of items drawn on screen.

    Basically, don't try and re-invent the wheel. I know this may not be the answer you are looking for, but it's almost certainly your best option.

    EDIT: I've fixed the attached fiddle (it was broken due to changes JSFiddle made to the site) but apparently SO won't let me save JSFiddle links without including some code, so...

    console.log("hello world!");