Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I achieve a percentage-based line length on an SVG with stroke-dasharray?

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

like image 291
Jimmy Rowe Avatar asked Oct 25 '25 02:10

Jimmy Rowe


1 Answers

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 :)

like image 72
Gaddy Evans Avatar answered Oct 26 '25 18:10

Gaddy Evans