{"id":254582,"date":"2017-05-08T07:11:20","date_gmt":"2017-05-08T14:11:20","guid":{"rendered":"http:\/\/css-tricks.com\/?post_type=chapters&p=254582"},"modified":"2021-10-06T07:36:58","modified_gmt":"2021-10-06T14:36:58","slug":"make-shape-draw","status":"publish","type":"chapters","link":"https:\/\/css-tricks.com\/books\/greatest-css-tricks\/make-shape-draw\/","title":{"rendered":"Self-Drawing Shapes"},"content":{"rendered":"\n

The best shape-drawing tool we have on the web is SVG, and in particular the <path d=\"\" \/><\/code> element. With the path syntax<\/a>, you can draw anything you want with its commands for drawing straight and curved lines. A path can be a solid shape, but for our purposes here, let’s assume the path is fill: none;<\/code> and we’ll focus on the stroke<\/code> of the path and having that path draw itself. <\/p>\n\n\n\n

Let’s say we have a single <path \/><\/code> that draws a cool shape like this:<\/p>\n\n\n\n

\"\"<\/figure>\n\n\n\n

In our SVG, we’ll make sure we’ve set up that path nicely like this:<\/p>\n\n\n\n

<path \n  pathLength=\"1\" \n  stroke=\"black\"\n  stroke-width=\"5\"\n  fill=\"none\"\n  d=\"...\"\n\/><\/code><\/pre>\n\n\n\n

That second line is going to make this trick very easy to pull off, as you’ll see in a moment. <\/p>\n\n\n\n

The trick itself, making the shape “draw itself” comes from the idea that strokes can be dashed<\/em>, and you can control the length and offset of the dashing<\/em>. So imagine this:<\/strong> you make the dash (and space after the dash) so long<\/em> that it covers the entire shape, so it appears as if didn’t dash the stroke at all. But then you offset the stroke that far again so that it looks like there is no stroke at all. Then here’s the key:<\/strong> animate the offset so it looks like the shape is drawing itself. <\/p>\n\n\n\n

That’s why pathLength=\"1\"<\/code> is so useful. We’re just animating offset from 1<\/code> to 0<\/code> which is easy as pie in CSS:<\/p>\n\n\n\n

path {\n  stroke-dasharray: 1;\n  stroke-dashoffset: 1;\n  animation: dash 5s linear forwards;\n}\n\n@keyframes dash {\n  from {\n    stroke-dashoffset: 1;\n  }\n  to {\n    stroke-dashoffset: 0;\n  }\n}<\/code><\/pre>\n\n\n\n

That CSS above will work on any<\/em> stroked path, assuming you’re using the pathLength<\/code> trick!<\/p>\n\n\n\n