【问题标题】:Get the rotate amount in animate a div through a SVG path通过 SVG 路径获取 div 动画的旋转量
【发布时间】:2013-01-28 19:24:20
【问题描述】:

来自我的last post 帮助通过 SVG 路径为 div 设置动画。成功和 div "#car" 动画通过我的路径。

现在的问题是如何根据曲线旋转/变换 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”的想法吗?

【问题讨论】:

    标签: html svg jquery-svg html5-animation svg-animate


    【解决方案1】:

    您需要计算曲线上两点之间的角度(例如,“汽车”的下边缘),公式如下:

    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/

    【讨论】:

    • 非常感谢... !!!!!!伟大的 !!!!你节省了我的时间!!!继续摇摆!!!谢谢先生!!!
    【解决方案2】:

    找到了一个很好的工具来轻松解决这个问题。

    那可能是你的朋友。

    https://github.com/yairEO/pathAnimator

    【讨论】:

      猜你喜欢
      • 2019-04-15
      • 2013-01-27
      • 1970-01-01
      • 2021-12-29
      • 2018-01-17
      • 2014-02-19
      • 1970-01-01
      • 2018-09-05
      • 2021-04-18
      相关资源
      最近更新 更多