Search code examples
javascriptsvgformulapixelscaletransform

How to convert scaling from SVG units to pixels using scale formula?


Previously, I asked how to obtain the real coordinates (d) of a path when a transformation is applied, finally I decided to investigate the transformation formulas, I have already seen the translation, and now I am seeing the scaling (scale), I managed to do a scaling Basically the formula is:

x’ = x * sx

y’ = y * sy

If I have a path where d attribute (command) of M5, 5 L50, 5 L50, 45 L5, 45 Z, and, If we inspect the path in the DOM, we'll find that it has a width of 135px and a height of 120px:

<svg width="300" height="300" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <rect x="0" y="0" width="100" height="100" fill="red" />
  <path id="element" d="M5, 5 L50, 5 L50, 45 L5, 45 Z" fill="none" stroke="white" />
</svg>

So if I wanted to scale this path using a scale factor of 2, it would be M10, 10 L100, 10 L100, 90 L10, 90, but if we now inspect the path in the DOM, the width is 270px and its height is 240px:

<svg width="300" height="300" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" width="100" height="100" fill="red" />
<path id="element" d="M10, 10 L100, 10 L100, 90 L10, 90 Z" fill="none" stroke="white" />
</svg>

Therefore, the value or scale factor of 2 is equivalent to a width of 135px and a height of 120px, so:

How can I make this scale factor or value equal to 1px?

Is there a conversion formula?

Playing around, I managed to guess that if the scale factor is:

1.1 = 15px -> therefore, the width would be 135px increasing to 150px and the height would be 120px increasing to 135px.

1.01 = 1.5px -> therefore, the width would be 135px increasing to 136.5px and the height would be 120px increasing to 121.5px.

I hope you have understood what I want to do, I hope you can help me.


Solution

  • I think I get what you are saying, but your formulas don't seem to make sense.

    1.1 = 15px -> therefore, the width would be 135px increasing to 150px and the height would be 120px increasing to 135px

    That "15px" seems wrong. 1.1 * 135 = 148.5, not 150.

    What I think you are asking is how to calculate the scale that would make the width become 150. Is that right?

    The scale that will get the width to exactly 150 can be calculated like this:

             new_width     150
    scale = ----------- = ----- = 1.1111...
             old_width     135
    

    So checking that: 135 * 1.1111... = 150.0.

    And the new height using this scale would be: 120 * 1.1111... = 133.333...