truly-daunting
truly-daunting

Reputation: 75

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);
    }
    });

Upvotes: 0

Views: 1977

Answers (2)

Robert Longson
Robert Longson

Reputation: 124179

You seem to be making this much harder than it needs to be by not using the SVG DOM. Resetting is merely a matter of changing the scale back to 1.

Here's some simplified code.

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

        $("#reset").click(function() {
                scale = 1.0 / $("#svgGroup")[0].transform.baseVal.getItem(0).matrix.a;
                zoom(scale);
        });

        function zoom(scale) {
                var transform = $("#svgGroup")[0].transform.baseVal.getItem(0);
                transform.matrix.a *= scale;
                transform.matrix.d *= scale;
                transform.matrix.e *= scale;
                transform.matrix.f *= scale;
        }
});

Upvotes: 1

QoP
QoP

Reputation: 28397

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

Upvotes: 2

Related Questions