Skip to content

Instantly share code, notes, and snippets.

@bendc
Created June 9, 2016 18:24
Show Gist options
  • Save bendc/319a295c92a8a33c737831416e7df81e to your computer and use it in GitHub Desktop.
Save bendc/319a295c92a8a33c737831416e7df81e to your computer and use it in GitHub Desktop.
SVG path bounding box
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