Skip to content

Instantly share code, notes, and snippets.

@Sphinxxxx
Created October 24, 2017 21:40
Show Gist options
  • Save Sphinxxxx/37394a43f13c3d31d3be7d3e07a81119 to your computer and use it in GitHub Desktop.
Save Sphinxxxx/37394a43f13c3d31d3be7d3e07a81119 to your computer and use it in GitHub Desktop.
//Replacement for
//https://developer.mozilla.org/en-US/docs/Web/API/SVGGeometryElement/getTotalLength
//Extracted from
//https://github.com/juliangarnier/anime/blob/master/anime.js
function getSvgTotalLength(el) {
function getDistance(p1, p2) {
return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}
function getCircleLength(el) {
return 2 * Math.PI * el.getAttribute('r');
}
function getRectLength(el) {
return (el.getAttribute('width') * 2) + (el.getAttribute('height') * 2);
}
function getLineLength(el) {
return getDistance(
{x: el.getAttribute('x1'), y: el.getAttribute('y1')},
{x: el.getAttribute('x2'), y: el.getAttribute('y2')}
);
}
function getPolylineLength(el) {
const points = el.points;
let totalLength = 0;
let previousPos;
for (let i = 0 ; i < points.numberOfItems; i++) {
const currentPos = points.getItem(i);
if (i > 0) totalLength += getDistance(previousPos, currentPos);
previousPos = currentPos;
}
return totalLength;
}
function getPolygonLength(el) {
const points = el.points;
return getPolylineLength(el) + getDistance(points.getItem(points.numberOfItems - 1), points.getItem(0));
}
//The way forward, but browser support is still poor (october 2017)
if (el.getTotalLength) return el.getTotalLength();
switch(el.tagName.toLowerCase()) {
case 'circle': return getCircleLength(el);
case 'rect': return getRectLength(el);
case 'line': return getLineLength(el);
case 'polyline': return getPolylineLength(el);
case 'polygon': return getPolygonLength(el);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment