I'm trying to achieve a percentage-based border-like effect on an SVG rect element, like the one shown in the image below. I've been advised that I need to use stroke-dasharray in order to do this, but despite playing around with a JSFiddle, I've been unable to find a solution that works universally for SVGs of any height and width. Any help or advice would be appreciated.
Here's what I'm currently playing around with in a JSFiddle:
<html>
<body>
<div>
<svg>
<rect
x="10"
y="10"
rx="10"
ry="10"
height="48"
width="48"
stroke-dasharray="50% 100%"
style="stroke: black; fill: none;"
/>
</svg>
</div>
</body>
</html>
Image of desired functionality
In this case, it is easiest to use the pathLength attribute with a value of 100. Then just define the stroke-dasharray attribute with a value that corresponds to the percentage of the desired length.
More info about pathLength at MDN Web Docs.
<html>
<body>
<div>
<svg>
<rect
x="10" y="10" rx="10" ry="10"
height="48" width="48"
pathLength="100"
stroke-dasharray="50"
stroke="#000"
fill="none" />
</svg>
</div>
</body>
</html>
No need to use Javascript :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With