Search code examples
htmlsvgjquery-svgsvg-animate

Animate a "div" through SVG path


I am a noob to HTML5, SVG. Basically I need to move a html "div" object through a SVG path which I created.

My HTML look like this

<div class="movepath">

        <div class="car" id="car"></div>


<svg id="canvas" width="1000px" class="content" xmlns="http://www.w3.org/2000/svg" height="370px">
<style type="text/css"><![CDATA[
    .lineC {
        fill:#fff;stroke:#000;
    }
]]></style>


</svg>

    </div>

CSS

.movepath {
width:"1000px";
height:350px;
position:relative;
float:left;
}

.car {
width:100px;
height:50px;
background-color:red;
position:absolute;
left:0;top:0;
}

js

var width=getDocWidth();
    $('#canvas').width(width+'px');
    $('.movepath').width(width+'px');



    var shape = document.createElementNS(svgNS, "path");

    var points = 'M0 10 Q -27 10, 95 80 T'+width+' 40';
    shape.setAttributeNS(null, "d", points);
    shape.setAttributeNS(null, "class", "lineC");
    shape.setAttributeNS(null, "id", 'road');
    document.getElementById("canvas").appendChild(shape);

Created a path like this. I am totally confused how to move $('#car') through created path ?

Please advice


Solution

  • Basically you need a loop (a function that is triggered in equal time steps, so no »for« or »while« loop), therein you need to get a point from the path like:

    length = path.getTotalLength() * i;
    point = path.getPointAtLength( length );
    

    than:

    div.style.left = point.x + 'px';
    div.style.top = point.y + 'px';
    

    where i is a value between 0 and 1 that represents the progress of your animation. All in all there is a bit more to know and there are different ways to move the div (i.e. css transforms), or get the values, but basically, that's it.