How stroke-dasharray Patterns Work

Say you have a line in SVG:

<svg>
  <line x1="0" y1="30" x2="500" y2="30" stroke-color="#f8a100" />
</svg>

You can use the stroke-dasharray property in CSS to make dashes:

line {
  stroke-dasharray: 5;
}

That 5 value is a relative unit based on the size of the SVG’s viewBox. We could use any CSS length, really. But what it does is make a pattern of dashes that are 5 units long with 5 unit gaps between them.

So far, so good. We can use two values where the second value individually sets the gap length:

Now we have dashes that are 5 units and gaps that are 10. Let’s try a third value:

See how we’re forming a pattern here? It goes:

  • Dash: 5 units
  • Gap: 10 units
  • Dash: 15 units

You’d think it repeats after that in the exact same cadence. But no! It if did, we’d have dashes bumping into one another:

  • Dash: 5 units
  • Gap: 10 units
  • Dash: 15 units
  • Dash: 5 units
  • Gap: 10 units
  • Dash: 15 units
  • …and so on.

Instead, stroke-dasharray gets all smart and duplicates the pattern if there are an odd number of values So…

stroke-dasharray: 5 10 15;

/* is the same as */
stroke-dasharray: 5 10 15 5 10 15;

That’s actually why a single value works! Earlier, we declared a single 5 value. That’s really the same as saying stroke-dasharray: 5 5. Without the second value, stroke-dasharray implicitly duplicates the first value to get a repeatable pattern. Otherwise, it’d just be a solid line of dashes that are 5 units long, but no gaps between them!

The pattern also depends on the size of the shape itself. Our SVG line is 500 units. Let’s set larger stroke-dasharray values and add them up:

stroke-dasharray: 10 20 30 40 50; /* 150 units */

If the pattern runs four times (150 units ⨉ 4 iterations), we’re dealing with 600 total units. That additional 100 units is lopped off to prevent the pattern from overflowing itself.

That’s all.

🎩 Hat tip to Joshua Dance for calling this out!


How stroke-dasharray Patterns Work originally published on CSS-Tricks. You should get the newsletter.

How to Get Handwriting Animation With Irregular SVG Strokes

I wanted to do a handwriting animation for calligraphy fonts — the kind where the words animate like they are being written by an invisible pen. Because calligraphy fonts have uneven stroke widths (they actually aren’t even strokes in terms of SVG), it was near impossible to do this sort of thing with typical path animation techniques. But I found an innovative application of SVG masking to achieve this affect in matter of minutes. 

While researching how to do this, I gathered information from multiple sources. I combined them together and was able to create the final effect.

Let’s make this together!

SVG masking

If the stroke width of all the letters in a word or sentence are even throughout, then Craig Roblewsky has a nice way to animate handwriting. This is a clever technique that animates the SVG stroke-dasharray and stroke-offset attributes.

Calligraphy fonts like we want to animate here have uneven stroke width throughout the letters, hence it will need to be a <path> and animating it in that way will not work. The trick will be to use SVG masking.

Let’s start by figuring out what font we want to use. The one I’ll be using throughout this article is HaveHeartOne, which has a nice brush stroke appearance that is perfect for handwriting.

The idea is to create a <mask> out of same sentence we want to animate, then place it on top of the sentence. In other words, there will be two layers of same sentence. Since the mask sits on top, we’ll make it white so it will hide the original sentence below it. We will animate the mask so the bottom layer is revealed as the animation runs.

Making the layers

The foundation of this trick is that we’re actually going to create two separate layers, one on top of the other:

  1. The bottom layer is the words with the desired font (in my case it is HaveHeartOne).
  2. The top layer is a handcrafted path approximating the words.

Creating the handcrafted path isn’t as hard as you might think. We need a continuous path to animate and reveal the sentence. That means no <text> for this. But, many illustrates apps — including Illustrator — can convert letters to paths:

  1. Select the words.
  2. Open the “Properties” panel and click Create outline.

And, like magic, the letters become outlines with vector points that follow the shape.

Showing the words Marketing Lab in red in Illustrator wrapped in blue vector points.
Imagine drawing all that by hand!

At this point it is very important to give meaningful names to these paths, which are stored as layers. When we expect this to SVG, the app will generate code and it uses those layer names as the IDs and classes.

Showing the Illustrator layers of the letters with proper naming.
Those names are much nicer that what would have been auto-generated.

Notice how individual letters have a fill but no stroke:

Showing the letter M selected in Illustrator with the properties panel open indicating there is no stroke on the shape.

In SVG, we can animate the stroke in the way we want to, so we’re going to need to create that as our second main layer, the mask. We can use the pen tool to trace the letters.

  1. Select the pen tool.
  2. Set the Fill option to “None.”
  3. The stroke width will depend on the font you’re using. I’m setting the Stroke Width option to 5px and setting its color to black.
  4. Start drawing!

My pen tool skills aren’t great, but that’s OK. What’s important isn’t perfection, but that the mask covers the layer below it.

Create a mask for each letters and remember to use good names for the layers. And definitely reuse masks where there are more than one of the same letter — there’s no need to re-draw the same “A” character over and over.

Showing the Marketing Lab letter shapes completely covered by the black outline layers.

Exporting

Next up, we need to export the SVG file. That will likely depend on the application you are using. In Illustrator, you can do that with File → Export → Export as → SVG

SVG options popup will open, below is the preferred setting to export for this example.

Showing the SVG export options in Illustrator.

Now, not all apps will export SVG the same exact way. Some do an excellent job at generating slim, efficient code. Others, not so much. Either way, it’s a good idea to crack open the file in a code editor 

When we’re working with SVG, there are a few tips to consider to help make them as light as possible for the sake of performance:

  1. The fewer points, the lighter the file.
  2. Using a smaller viewBox can help.
  3. There are plenty of tools to optimize SVG even further.

Manually editing the SVG code

Now, not all apps will export SVG the same exact way. Some do an excellent job at generating slim, efficient code. Others, not so much. Either way, it’s a good idea to crack open the file in a code editor and make a few changes.

Some things worth doing:

  1. Give the <svg> element width and height attributes that are set to size the final design.
  2. Use the <title> element. Since we’re working with paths, the words aren’t actually recognized by screen readers. If you need them to be read when in focus, then this will do the trick.
  3. There will likely be group elements (<g>) with the IDs based on the layers that were named in the illustration app. In this specific demo, I have two group elements:  #marketing-lab (the outline) and #marketing-masks (the masks). Move the masks into a <defs> element. This will hide it visually, which is what we want.
  4. There will likely be paths inside of the masks group. If so, go ahead and remove the transform attribute from them.
  5. Wrap each path element in a <mask> and give them a .mask class and an ID that indicates which letter is masked.

For example:

<mask id="mask-marketing-M">
  <path class="mask" id="mask-M" ... />
</mask>

Inside the outline group (which I’ve given an ID of #marketing-lab), apply the mask to the respective character path element by using mask="url(#mask-marketing-M)".

<g id="marketting-lab">
  <path mask="url(#mask-marketing-M)" id="marketting-char-M" d="M427,360, ... " />
</g>

Here’s the code for one character using all the above modifications:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 381 81" class="marketing-lab">
  <title>Marketing Lab</title>
  <defs>
    <g id="marketing-masks">
      <mask id="mask-marketing-M">
        <path class="mask" id="mask-M"
          d="M375.5, ... ,9-10" stroke-linecap="square" stroke-linejoin="bevel" stroke-width="7" />
      </mask>
    </g>
  </defs>
  <g id="marketting-lab">
    <path
      mask="url(#mask-marketing-M)" id="marketting-char-M" 
      d="M427,360.22c-.11.08-.17.14-.17.18H427c0" />
  </g>
</svg>

Finally, we will add CSS for the .mask element that overrides stroke color with white so it is hidden against the document’s background color.

.mask {
  fill: none;
  stroke: #fff;
}

Animation

We’re going to animate the CSS stroke-dasharray property to get the continuous line reveal effect. We can do the animation with either CSS and JavasScript or with Greensock (GSAP). We’ll look at both approaches.

CSS and JavaScript 

It’s fairly straightforward to do this in CSS alone. You can use JavaScript to calculate the path length and then animate it using that returned value. If you do not want to use JavaScript at all, then you can calculate the path length once and hardcode that value into the CSS.

/* Set the stroke-dasharray and stroke-dashoffset */
.mask {
  stroke-dasharray: 1000;
  stroke-dashoffset: 1000;
}


/* Animation the stroke-dashoffset to a zero length */
@keyframes strokeOffset {
  to {
    stroke-dashoffset: 0;
  }
}


/* Apply the animation to each mask */
#mask-M {
  animation: strokeOffset 1s linear forwards;
}

JavaScript can help with the counting if you’d prefer to go that route instead:

// Put the masks in an array
const masks = ['M', 'a', 'r', 'k-1', 'k-2', 'e', 't-line-v', 't-line-h', 'i-2', 'i-dot', 'n', 'g', 'lab-l', 'lab-a', 'lab-b']


masks.forEach((mask, index, el) => {
  const id = `#mask-${mask}` // Prepend #mask- to each mask element name
  let path = document.querySelector(id)
  const length = path.getTotalLength() // Calculate the length of a path
  path.style.strokeDasharray = length; // Set the length to stroke-dasharray in the styles
  path.style.strokeDashoffset = length; // Set the length to stroke-dashoffset in the styles
})

GSAP

GSAP has a drawSVG plugin which allows you to progressively reveal (or hide) the stroke of an SVG <path>, <line>, <polyline>, <polygon>, <rect>, or <ellipse>. Under the hood, it’s using the CSS stroke-dashoffset and stroke-dasharray properties. 

Here’s how it works:

  1. Include GSAP and drawSVG scripts in the code.
  2. Hide the graphic initially by using autoAlpha.
  3. Create a timeline.
  4. Set autoAlpha to true for the graphic.
  5. Add all the character path masks IDs to the timeline in proper sequence.
  6. Use drawSVG to animate all characters.

References

  1. Animated Drawing Line in SVG by Jake Archibald
  2. Creating My Logo Animation by Cassie Evans

The post How to Get Handwriting Animation With Irregular SVG Strokes appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Line-Animated Hamburger Menu

This kind of SVG + CSS animation trickery is catnip to me. Mikael Ainalem shares how to draw a hamburger icon (the “three lines” thing you’re well familiar with), but then animate it in a way that is surprising and fun by controlling the SVG properties in CSS.

The trick is that the top and bottom lines aren’t just a straight <line /> but a <path /> that curves up, down, and around forming the cross. You can only see part of the line (making it appear straight at first) because the stroke-dasharray only reveals part of the line. Then, by animating both the stroke-dasharray and stroke-dashoffset, the ✕ is formed.

Direct Link to ArticlePermalink

The post Line-Animated Hamburger Menu appeared first on CSS-Tricks.

A Trick That Makes Drawing SVG Lines Way Easier

When drawing lines with SVG, you often have a <path> element with a stroke. You set a stroke-dasharray that is as long as the path itself, as well as a stroke-offset that extends so far that you that it's initially hidden. Then you animate the stroke-offset back to 0 so you can watch it "draw" the shape.

Figuring out the length of the path is the trick, which fortunately you can do in JavaScript by selecting the path and doing pathEl.getTotalLength(). It'll probably be some weird decimal. A smidge unfortunate we can't get that in CSS, but c'est la vie.

Here's the trick!

You don't have to measure the length of the path, because you can set it.

So you do like:

<path d="M66.039,133.545 ... " pathLength="1" />

That doesn't do anything by itself (as far as I know). It's not like that only draws part of the path — it still draws the whole thing like as if you did nothing, only now the "math" of the path length is based on a value of 1.

Now we can set the stroke-dasharray to 1, and animate the offset in CSS!

.path {
  stroke-dasharray: 1;
  stroke-dashoffset: 1;
  animation: dash 5s linear alternate infinite;
}

@keyframes dash {
  from {
    stroke-dashoffset: 1;
  }
  to {
    stroke-dashoffset: 0;
  }
}

Which works:

See the Pen
Basic Example of SVG Line Drawing, Backward and Forward
by Chris Coyier (@chriscoyier)
on CodePen.

High five to Adam Haskell who emailed me about this a few months back.


Hey, speaking of SVG line drawing: Lemonade made a landing page for their 2019 charity that uses scroll-triggered SVG line drawing up and down the entire page. They did a behind-the-scenes look at it, which I always appreciate.

animated GIF of line drawing on Lemonade page - as page scrolls down a teddy bear shape is drawn

The post A Trick That Makes Drawing SVG Lines Way Easier appeared first on CSS-Tricks.