How do the stroke-dasharray numbers work?

966 views Asked by At

I am playing around with a cool effect that I found on codepen here:

https://codepen.io/P3R0/pen/zxabvb

I want to make the dashes on this svg animation shorter, and believe I have found the css element which does this:

stroke-dasharray: 70 330;

When I reduce 70 to 30 for example, the dashes become shorter which is good. However you will notice they no longer glide around smoothly - they now jump position.

I've been searching and trying to understand how stoke-dasharray works, but can't work it out. Can anyone explain to me how these numbers work and how I can make shorter dashes which still glide around smoothly.

Thanks for any help.

2

There are 2 answers

1
İlknur Ültanır On

The first parameter of the stroke-dasharray is the length of the filled area and the second one is the total length of the shape. You can fix your animation by shortening the total length as below.

stroke-dasharray: <filled-length> <total-length>;

stroke-dasharray: 30 150;
0
Joshua Dance On

stroke-dasharray's confused me for a long time. Until I finally figured it out.

I made a full codepen that explains it with examples. https://codepen.io/joshdance-the-sans/pen/oNqzRym

If you read the docs stroke-dasharray: "specify the lengths of alternating dashes and gaps. If an odd number of values is provided, then the list of values is repeated to yield an even number of values.

So the numbers are just a repeating list of: dash length, gap length, dash length, gap length

Which is repeated around the whole shape.

In your example:

stroke-dasharray: 70 330;

70 is the dash length, and 330 is the gap length. This makes sense because there are 5 different colors, which is done by copying the SVG 5 times, and adding a different stroke color to each. Stroke length + gap length is 70 + 330 = 400 and they are offsetting the strokes by 400 in the keyframes.

@keyframes stroke {
  100% {
    stroke-dashoffset: -400;
  }
}

Your example is cool, but complex as it has animation as well as multiple different strokes. Check out my codepen and play with the CSS for a simpler example to understand. Good luck!