2013-02-13 55 views
1

从我的last post帮助通过SVG路径动画div。通过我的路径成功和div“#car”动画。通过SVG路径获取动画div中的旋转量

现在的问题是如何根据曲线旋转/转换div?也就是说,如果它通过索道移动需要根据线的曲线旋转div。

HTML部分

<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部分

$(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; 
} 

任何一个可以请给我一个旋转 “#car” 的想法根据路径?

回答

2

你需要计算沿曲线两点之间的角度(比如,你的“车”的下缘),该公式将是这样的:

function getAngle(p1, p2) { 
    var deltaY = p2.y - p1.y; 
    var deltaX = p2.x - p1.x; 
    return Math.atan2(deltaY, deltaX) * 180/Math.PI 
} 

这里是一个粗略的工作示例您代码:

http://jsfiddle.net/5CB4u/

+0

非常感谢...... !!!!!太好了!你节省了我的时间!保持摇摆!谢谢你,先生 !!! – ramesh 2013-02-14 04:16:38