Search code examples
svgscaletransformation

svg scale rect so that corners overlap


I have a rect with top left corner at (x1,y1), rendered with svg. When I rescale this rect, I want the top left corner of the new rect, to be at the same coordinate (x1,y1). Is there a Formula to translate the resized Rect, so that this can happen?

Even better, is there a more general approach, so that the rect can overlap with the corner of my choice?

Corners should overlap, when rescaling

EDIT: I added this jsfiddle example I found: here . I have a rect:

<rect id="square" x="15" y="15" width="20" height="20" 
style="fill: none; stroke:black" />

<use xlink:href="square" transform="scale(5)" />

I want both rects to have the same coordinate (15,15) for their topleft corner


Solution

  • I'm not sure if you wanted the big rect to stay that size or if you wanted to scale down, so I have two solutions for you.

    1. The simple way of matching both rects' coords is to scale down the big one. If you set the scale(1) , the big one will scale down to the size of the original and they'd be both at (15, 15) . The side affect of transform=scaling is that the coords change accordingly. So if the big rect is scaled down from 5 then divide it's dimensions (200x200) by 10 and it's coordinates + stroke width.(75,75) by 5.

    2. The other way is if your intentions were to keep the size of the big rect at 200x200. You can move it with transform=translate(-12.5,-12.5) The reason why it's not (-15,-15) is because it's stroke is 5px wide.

    CODEPEN

    Both solutions are on the demo #1 is commented out.