Created
January 30, 2015 14:57
-
-
Save Torthu/55507ed5383fbb25dafa to your computer and use it in GitHub Desktop.
Get absolute position (from 0,0) for a SVG element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Find the position of a SVG DOM element | |
getPosition = (element) -> | |
# We have a transform, that might contain a translate(x,y) | |
transform = element.getAttribute('transform') | |
if transform? | |
match = transform.match(/translate\(\s*(-?[\d.]*)\s*[,]\s*(-?[\d.]*)\s*/) | |
# We have translate(x,y) | |
if match?.length >= 2 | |
x = parseFloat(match[1]) | |
y = parseFloat(match[2]) | |
# We try to get x="" and y="" | |
else | |
x = element.getAttribute('x') | |
y = element.getAttribute('y') | |
# Set x and y to 0 if they are undefined or null | |
x ?= 0 | |
y ?= 0 | |
return {x:x, y:y} | |
# Find absolute position of a SVG DOM element | |
findAbsolutePosition = (element) -> | |
abspos = {x:0,y:0} | |
# While we have DOM elements, get position and go to parent | |
while(element.getAttribute?) | |
pos = getPosition(element) | |
if pos and typeof pos.x is 'number' | |
abspos.x+=pos.x | |
abspos.y+=pos.y | |
element = element.parentNode | |
return abspos |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment