3

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

ramesh
  • 4,008
  • 13
  • 72
  • 117

1 Answers1

3

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.

philipp
  • 15,947
  • 15
  • 61
  • 106
  • thanks for the reply .. is this ok ? var length=$('#road').getTotalLength() * i; var point=$('#road').getPointAtLength( length ); – ramesh Feb 12 '13 at 06:12
  • var length=$('#road')[ 0 ].getTotalLength() * i; – philipp Feb 12 '13 at 06:36
  • thank you for your reply ... it works, but it wont tilting according to the curve. I mean moving straightly ... Is there any method to change the origin of the moving div ? – ramesh Feb 13 '13 at 06:32
  • If you use css3 transformations you can rotate the div, too. To get the angle you can use the first derivation of the curve on the specific point. look here http://processingjs.nihongoresources.com/bezierinfo/ for more information about the curves anatomy. It is possible, but more advanced. – philipp Feb 13 '13 at 07:32