nb_ck nb_ck - 5 months ago 158
CSS Question

How to animate handwriting text on the web page using SVG?

I am trying to animate a text that I created and saved as SVG. So far I was able to animate the stroke only, but it is not what I am trying to achive.
Here is the link to the example what I need:

[http://codepen.io/se7ensky/pen/waoMyx][1]

[https://codepen.io/munkholm/pen/EaZJQE][1]


I will really appreciate if some one can explain how I Can implement this.

Here is what I have so far:

[https://codepen.io/sora1/pen/LZNZva][1]

Answer

How the Se7ensky animation works is that it uses the standard dash animation technique, but clips the animated stroke with an outline representing the hand-drawn look of the logo.

So the standard dash animation technique works as follows. You take a standard line:

<svg>
  <path d="M 10,75 L 290,75" stroke="red" stroke-width="50"/>
<svg>

Then you add a dash pattern to it and animate it's position (stroke-dashoffset).

.pen {
  stroke-dasharray: 280 280;
  stroke-dashoffset: 280;
  animation-duration: 2s;
  animation-name: draw;
  animation-iteration-count: infinite;
  animation-direction: alternate;
  animation-timing-function: linear;
}

@keyframes draw {
  from {
    stroke-dashoffset: 280;
  }

  to {
    stroke-dashoffset: 0;
  }
}
<svg>
  <path class="pen" d="M 10,75 L 290,75" stroke="red" stroke-width="50"/>
<svg>

Finally to get the fancy variable stroke width of the Se7ensky example, you clip that line with the outline of your logo.

So let's pretend this simple path below represents your logo:

<svg>
  <path stroke="black" stroke-width="1" fill="lightgrey"
        d="M 40,50
           C 110,55 195,60, 265,55
           C 290,55 290,85 265,85
           C 195,85 110,85 40,100
           C 0,100 0,50 40,50 Z"/>
<svg>

We turn that into a clipPath element and use it to trim our animated stroke to the shape of our logo:

.pen {
  stroke-dasharray: 280 280;
  stroke-dashoffset: 280;
  animation-duration: 2s;
  animation-name: draw;
  animation-iteration-count: infinite;
  animation-direction: alternate;
  animation-timing-function: linear;
}

@keyframes draw {
  from {
    stroke-dashoffset: 280;
  }

  to {
    stroke-dashoffset: 0;
  }
}
<svg>
  <clipPath id="logo">
    <path d="M 40,50
             C 110,55 195,60, 265,55
             C 290,55 290,85 265,85
             C 195,85 110,85 40,100
             C 0,100 0,50 40,50 Z"/>
  </clipPath>
  
  <path class="pen" d="M 10,75 L 290,75" stroke="red" stroke-width="50" clip-path="url(#logo)"/>
<svg>

So to replicate their example, you'll need to add a continuous path (or paths if you want) to your SVG that represents the path that a pen would take if it were writing the letters in your logo.

Then animate that path using the dashoffset technique while clipping it with your original logo.