Created
June 9, 2016 18:24
-
-
Save bendc/319a295c92a8a33c737831416e7df81e to your computer and use it in GitHub Desktop.
SVG path bounding box
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
const getPathBoundingBox = (() => { | |
const toPolygon = (path, points = 50) => { | |
const polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon"); | |
const total = path.getTotalLength(); | |
const step = total / points; | |
const getPoints = (dist = 0, arr = []) => { | |
const {x, y} = path.getPointAtLength(dist); | |
arr.push(`${x},${y}`); | |
const next = step + dist; | |
return next > total ? arr : getPoints(next, arr); | |
} | |
polygon.setAttribute("points", getPoints().join(" ")); | |
return polygon; | |
}; | |
return path => { | |
const polygon = toPolygon(path); | |
const parent = path.parentNode; | |
polygon.setAttribute("fill", "none"); | |
parent.appendChild(polygon); | |
const rect = polygon.getBoundingClientRect(); | |
parent.removeChild(polygon); | |
return rect; | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment