通过SVG路径为“div”设置动画

时间:2013-02-12 05:52:49

标签: html5 svg jquery-svg svg-animate

我是HTML5,SVG的菜鸟。基本上我需要通过我创建的SVG路径移动一个html“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

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);

创建了这样的路径。我完全混淆了如何通过创建的路径移动$('#car')?

请咨询

1 个答案:

答案 0 :(得分:2)

基本上你需要一个循环(一个以相等的时间步长触发的函数,所以没有»for«或»while«loop),其中你需要从路径中得到一个点,如:

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

比:

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

其中i是介于0和1之间的值,表示动画的进度。总而言之,还有一点需要知道,有不同的方法来移动div(即css变换),或获取值,但基本上就是这样。

相关问题