Search code examples
svgsvg-animate

SVG Animate polilines transition


Could anyone post an example of how to animate svg polyline or path?

I want to animate a transition from blue to gray lines. Ideally I'm looking for a solution which works out of whatever gray line is without knowing the number of coordinates of its' points.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <div style="height: 200px; width: 500px; border: 1px solid #ccc;">

        <svg height="200" width="500" xmlns="http://www.w3.org/2000/svg">
            <polyline points="20,20 40,25 60,40 80,120 120,140 200,180"
                      style="fill: none; stroke: gray; stroke-width: 3" />

            <polyline points="20,20 40,20 60,20 80,20 120,20 200,20"
                      style="fill: none; stroke: blue; stroke-width: 3" />
        </svg>
    </div>
</body>
</html>

Solution

  • You can animate a polyline using SMIL via the animate tag. If you need IE support then you'd have to use something like fakeSmile.

    You will need to keep the number of points the same i.e. if you have a 10 point polygon you'll have to transition it to a 10 point polygon to get a smooth transition otherwise it will do step change transitions. You can always double up points on one of the polygon to make them have the same number of points.

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
    <body>
        <div style="height: 200px; width: 500px; border: 1px solid #ccc;">
    
            <svg height="200" width="500" xmlns="http://www.w3.org/2000/svg">
                <polyline points="20,20 40,20 60,20 80,20 120,20 200,20"
                          style="fill: none; stroke: blue; stroke-width: 3">
                    <animate dur="5s" fill="freeze" attributeName="points"
                             to="20,20 40,25 60,40 80,120 120,140 200,180"/>
                    <animate dur="5s" fill="freeze" attributeName="stroke"
                             to="gray"/>
                </polyline>
            </svg>
        </div>
    </body>
    </html>