I am working on a project that moves elements of an svg file up and down across a horizontal line. I want to track the position of the moving element in relation to the fixed line. Both elements are within the same svg. I tried using
getBoundingClientRect().top
However, this does not provide a good solution as the coordinates produced by the getBoundingClientRect() function change based on the size, position, and zoom, of the viewport. It is not the same for every device in every situation. I need to be able to know when a specific path is a certain distance above or below a fixed line. I'm using setAttribute('transform','translate()) on the containing group to move a group of objects in my project. I need to know the position of an individual object within my group in relation to a fixed line not in my group.
<svg version="1.1" id="ex1-3rds-quarter-s" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
y="0px" width="323.333px" height="55.333px" viewBox="0 0 323.333 55.333" enable-background="new 0 0 323.333 55.333"
xml:space="preserve">
<g id="ledgerlines">
<line id="MidCLine1" fill="none" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" x1="48.09" y1="41.694" x2="57.924" y2="41.694"/>
</g>
<g id="note1">
<path class="root" d="M54.113,38.945c1.116,0,2.172,0.578,2.172,1.813c0,1.435-1.116,2.411-2.052,2.969c-0.717,0.418-1.514,0.717-2.331,0.717
c-1.116,0-2.172-0.578-2.172-1.813c0-1.435,1.116-2.411,2.052-2.969C52.499,39.244,53.296,38.945,54.113,38.945z"/>
<path d="M54.113,33.963c1.116,0,2.172,0.578,2.172,1.813c0,1.435-1.116,2.411-2.052,2.969c-0.717,0.418-1.514,0.717-2.331,0.717
c-1.116,0-2.172-0.578-2.172-1.813c0-1.435,1.116-2.411,2.052-2.969C52.499,34.262,53.296,33.963,54.113,33.963z"/>
</g>
</svg>
Is there a way to track the position of the path without using the getBoundingClientRect() function?
Thanks, --christopher
Try placing your path in an svg 'wrapper/empty' element. Then use
getBBox()
for the wrapper. This will provide x,y values used to set/read the path's translations.EDIT: I have included an example below that can move rects between reference lines. This works even when the rect has been previously transformed. This uses a single SVG Wrapper. Note: If you are only going to transform your element a single time, then you do not have to use the matrix transform on the bbx, bby values. they can be used directly.