Search code examples
svginkscape

SVG | y-coordinate is different


The svg file: http://pastebin.com/8N61VpS1

enter image description here

<rect
   style="fill:#000000"
   id="rect3409"
   width="166.39345"
   height="180.32787"
   x="77.049179"
   y="611.37854" />

The rectangle "rect3409" has coordinates (x,y) = (77.049, 260.656) in Inkscape 0.91 r13725.

However, the tag <rect> with id rect3409 has (x, y) = (77.049, 611.379). Why are there differences between the two?

I want to get the correct SVG coordinate of the rectangle. How do I do that?


Solution

  • If you look at the source, you'll see that #rect3409 has a parent g element:

    <g transform="translate(0,-452.36216)">
      <!-- snip -->
      <rect
        id="rect3409"
        width="166.39345"
        height="180.32787"
        x="77.049179"
        y="611.37854" />
    </g>
    

    The transform=translate(tx, ty) attribute on the g is applied to the dimensions of #rect3409. So the vertical axis of the rect goes from y + ty to y + h + ty, which is 611 - 452 == 159px to 611 + 180 - 452 == 339px. I think these are the "correct SVG co-ordinate" values you want.

    But Inkscape is not reporting these values, but rather 261px to 441px. It seems like Inkscape is actually flipping the y axis: in SVG (and conventionally in all computer graphics) y=0 is at the top of the screen, and y increases as you move down the screen. For example, the following SVG displays a red box above a blue box:

    <svg>
      <rect x="0" y="0" width="10" height="10" fill="red" />
      <rect x="0" y="10" width="10" height="10" fill="blue" />
    </svg>
    

    In Inkscape, however, you have the mathematical convention of y=0 at the bottom, and y increasing as you go upwards. Therefore, the co-ordinates you see in Inkscape are modified from the "true" SVG co-ordinates (thanks @squeamish ossifrage for pointing this out in the comments): y_Inkscape = h_image - y_SVG, where y_Inkscape is what Inkscape tells, you, y_SVG is what's in the file, and h_image is the total image height.

    Your sample image is exactly 600px high, so the "Inkscape" co-ordinates of #rect3409 are
    600 - 339 == 261px, and
    600 - 159 == 441px.