【问题标题】:Animate a "div" through SVG path通过 SVG 路径为“div”设置动画
【发布时间】:2013-01-27 09:22:43
【问题描述】:

我是 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') ?

请指教

【问题讨论】:

    标签: html svg jquery-svg svg-animate


    【解决方案1】:

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

    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 转换)或获取值,但基本上就是这样。

    【讨论】:

    • 感谢您的回复.. 可以吗? var length=$('#road').getTotalLength() * i; var point=$('#road').getPointAtLength(length);
    • var length=$('#road')[ 0 ].getTotalLength() * i;
    • 谢谢您的回复...它可以工作,但它不会根据曲线倾斜。我的意思是直线移动...有什么方法可以改变移动div的原点吗?
    • 如果您使用 css3 转换,您也可以旋转 div。要获得角度,您可以使用特定点上曲线的一阶导数。看这里processingjs.nihongoresources.com/bezierinfo 了解更多关于曲线解剖的信息。这是可能的,但更高级。
    猜你喜欢
    • 2012-07-14
    • 2013-03-18
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 2013-01-28
    相关资源
    最近更新 更多