Let’s say you want to create an animation that draws some kind of shape. Like watching a pencil draw a line on paper. Turns out this is really easy with SVG paths.
One way of creating a shape is by creating it as an SVG path. This is exactly what it sounds like. It’s a directional outline of a shape, or a way of drawing a curvy line from point A to point B. You can draw along this path with different stroke styles (solid, dashed, etc). The neat thing about creating a dashed line along a path is that you can control the length of the dashes. What happens if you make the dash as long as the line? Magic.
If you create a path, and then specify the dash length to be much greater than the path itself, you can animate the dash offset to give the effect of “drawing” along that path. Here’s how you do it:
- Create a path (see RaphaelJS)
- Set the properties:
path-dashoffsetto be equal, and a pixel value much greater than the path itself (eg: 99999px). Let’s call this
- Animate the
path-dashoffsetfrom its starting value, to the value of the
path-dasharrayminus the path length (
maxLen - path length). You can use jQuery for this.