-
-
Notifications
You must be signed in to change notification settings - Fork 889
Get the exact length for a custom shape
When you create a custom shape (see tutorial Shape & Swirl) you can define it's length with the getLength
method, - it is handy only if you want to use relative percent values for strokeDasharray
/strokeDashoffset
properties.
/* ADD CUSTOM SHAPE */
class Heart extends mojs.CustomShape {
getShape () { return '<path d="M92.5939814,7.35914503 C82.6692916,-2.45304834 66.6322927,-2.45304834 56.7076029,7.35914503 L52.3452392,11.6965095 C51.0327802,12.9714696 48.9328458,12.9839693 47.6203869,11.6715103 L47.6203869,11.6715103 L43.2705228,7.35914503 C33.3833318,-2.45304834 17.3213337,-2.45304834 7.43414268,7.35914503 C-2.47804756,17.1963376 -2.47804756,33.12084 7.43414268,42.9205337 L29.7959439,65.11984 C29.7959439,65.1323396 29.8084435,65.1323396 29.8084435,65.1448392 L43.2580232,78.4819224 C46.9704072,82.1818068 52.9952189,82.1818068 56.7076029,78.4819224 L70.1696822,65.1448392 C70.1696822,65.1448392 70.1696822,65.1323396 70.1821818,65.1323396 L92.5939814,42.9205337 C102.468673,33.12084 102.468673,17.1963376 92.5939814,7.35914503 L92.5939814,7.35914503 Z"></path>'; }
getLength () { return 292.110107421875; } // optional
}
There is different ways you can calculate this value:
If your custom shape only consist of path elements, you could calculate each path's length with the SVGPathElement method getTotalLength()
(read more about SVGPathElement on MDN).
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<path id="shape" d="M0 0 H 100 V 100 H 0 L 0 0"/>
</svg>
console.log(
document.getElementById( 'shape' )
.getTotalLength()
);
See on CodePen: https://codepen.io/sandstedt/pen/dXmmVN
Select the shape and select Object in the Document Info panel (make sure to have PX as measurement). If you have multiple objects, you could just select all and Illustrator will add the total length of them together.
If you have multiple paths (or lines, polylines, polygons etc), you have to decide if you want to return the length of the longest path, the shortest, or something in between. Each resulting in different effects. See example on CodePen.