truly-daunting truly-daunting - 5 months ago 20
jQuery Question

Reset SVG to original transform matrix

I'm trying to reset my SVG back to its original transform matrix attribute. I have a scale function which uses this matrix to zoom in and out of the SVG. However, I want to be able to reset the SVG back to the transform matrix it first had.

I first load the transform matrix attribute into an array, which I then use in my scale function.

How can I store the original values so they won't be touched by my scale function, and so I can use them to reset the SVG?

Here is my JSfiddle

This is my script:

$(document).ready(function() {
var newMatrix;
var transMatrix = $("#svgGroup").attr("transform").replace(/[^0-9.,]+/, "");
transMatrix = transMatrix.split(",");
var origMatrix = [1,0,0,1, parseFloat(transMatrix[4]), parseFloat(transMatrix[5])];

$("#out").click(function() {
zoom(0.8)
});
$("#in").click(function() {
zoom(1.25);
});

$("#reset").click(function() {
alert(origMatrix)
$("#svgGroup").attr("transform", "matrix(" + origMatrix + ")");
});

function zoom(scale) {
for (var i=0; i<origMatrix.length; i++) {
origMatrix[i] *= scale;
}
newMatrix = "matrix(" + origMatrix.join(' ') + ")";
$("#svgGroup").attr("transform", newMatrix);
}
});

QoP QoP
Answer

You have to deep clone the original array. In order to do it, use .slice(0)

var origMatrix = [1,0,0,1, parseFloat(transMatrix[4]), parseFloat(transMatrix[5])];
var initialValue = origMatrix.slice(0);

Now you can use it in your reset function.

$("#reset").click(function() {
          origMatrix = initialValue.slice(0);
          $("#svgGroup").attr("transform", "matrix(" + origMatrix + ")");
});

jsfiddle