Search code examples
javascriptjquerysvgjquery-svgsvg-edit

Positioning a transformed SVG element within an svg-canvas


I have written a function that will resize an SVG path, or any shape. However when i use it the path does gets resized but unfortunatetly it also changes position within my svg-canvas.

this is my function

    function output() 
    {
       var transformw=prompt("Enter your new width");
       var transformh=prompt("Enter your new height");
       var lastw = svg_1.getBoundingClientRect().width;
       var lasth = svg_1.getBoundingClientRect().height;

       newW=transformw/lastw;
       newH=transformh/lasth;
       alert(newH);
       alert(newW);

       svgCanvas.changeSelectedAttribute("transform", 
            "matrix(" + newW + ", 0, 0, " + newH + ", 0, 0)");

       svgCanvas.recalculateAllSelectedDimensions();
    }

I only want the shapes to be positioned on the top corner of my canvas once they get transformed. Ideally i would want them to have the same x,y position they had before the transformation however i wouldnt mind to have a fixed point if the original x,y position is difficult to achieve.


Solution

  • i am answering my own question.

    When we resize an SVG element using transform the elements gets moved in the x,y axis relative to the transformation we did.

    To counteract this effect we just need to apply a negative translation on the element that has the same ''transformation'' parameters albeit negatively(it moves it to the opposite direction than what the transformation does.

    This way we counteract the positioning effects of a tranformation and we only get the resizing effects.