From my last post helped to animate a div through a SVG path. Success and div "#car" animating through my path.
Now the problem is how to rotate/ transform the div according to the curve ? ie if it moving through a slanding path need to rotate the div according to the curve of line.
HTML Part
<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 Part
.movepath {
width:"1000px";
height:350px;
position:relative;
float:left;
}
.car {
width:100px;
height:50px;
background-color:red;
position:absolute;
left:0;top:0;
}
JS Part
$(document).ready(function(){
timer=setInterval('rotateIt()',20);
var width=getDocWidth();
$('#canvas').width(width+'px');
$('.carpath').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);
});
function rotateIt(){
rot += 10;
left+=1;
$('.right_t').css(prefix, 'rotate(' + rot + 'deg)');
$('.left_t').css(prefix, 'rotate(' + rot + 'deg)');
var length=$('#road')[0].getTotalLength() * i;
var point = $('#road')[0].getPointAtLength( length );
$('#car').css('left',point.x+'px');
$('#car').css('top',(point.y-62)+'px');
i+=.0005;
}
Can any one please give me an idea for rotate "#car" according to the path ?
You need to calculate the angle between two points along the curve (say, the lower edges of your "car"), the formula would be this:
function getAngle(p1, p2) {
var deltaY = p2.y - p1.y;
var deltaX = p2.x - p1.x;
return Math.atan2(deltaY, deltaX) * 180 / Math.PI
}
Here is a rough working example with your code: