【问题标题】:Animate SVG path with d3js使用 d3js 为 SVG 路径设置动画
【发布时间】:2014-01-07 01:06:50
【问题描述】:

我使用标准 SVG 笔标记(“M 130 30”、“L 132、40”等)定义了一个非常复杂的路径。如何获取此标记并创建一条路径,以便我可以按照此处所述缓慢绘制整个路径?:Can't make paths draw growing slowly with D3

【问题讨论】:

    标签: javascript animation svg d3.js


    【解决方案1】:

    即使要设置动画的<path> 节点不是由D3 生成的,该问题中duopixel's answer 中列出的方法仍然有效。这是使用现有 SVG 路径节点的 duopixel's code 的修改版本:

    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    </head>
    <body>
        <svg xmlns="http://www.w3.org/2000/svg" id="visualization" height="300" width="700">
            <path id="existingLine" fill="none" stroke-width="2" stroke="steelblue" 
            d="M0,45.355864964297126Q56,93.30709264413157,70,101.42710214950955C91,113.60711640757651,119,112.60236634997189,140,126.5559600180769S189.00000000000003,192.28891292428457,210.00000000000003,194.45105993687628S259,143.07483109253366,280,140.97027343535498S329,190.98168538928422,350,180.42067555568514S399.00000000000006,58.614334097794526,420.00000000000006,70.56354121136098S469.00000000000006,240.5996349725512,490.00000000000006,260.08205631279486S539,201.70472761196623,560,200.44635014631868S609,277.9853193478483,630,251.69287320847783Q644,234.16457578223088,700,25.163375883849042">
            </path>
        </svg>
      <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
      <script type="text/javascript">
        // select the already-existing path node via its ID.
        var path = d3.select("#existingLine");
    
        // from here forward the code is exactly like the original....
        var totalLength = path.node().getTotalLength();
    
        path
          .attr("stroke-dasharray", totalLength + " " + totalLength)
          .attr("stroke-dashoffset", totalLength)
          .transition()
            .duration(2000)
            .ease("linear")
            .attr("stroke-dashoffset", 0);
    
      </script>
    </body>
    </html>
    

    或者,如果您确实想使用 D3 创建节点,只需使用您现有的路径字符串并使用它来代替 line() 函数调用。再次调整 duopixel 的代码:

    var path = svg.append("path")
      .attr("d", "M 130 30", "L 132, 40") // and so on
      .attr("stroke", "steelblue")
      .attr("stroke-width", "2")
      .attr("fill", "none");
    

    【讨论】:

    • 所以这似乎同时绘制了所有线条。我希望它按照路径中指定的顺序绘制它 - 一次绘制一条线。我可以用这段代码做到这一点吗?具体来说,似乎所有 M 动作都在 time=0 时运行,而不是一个接一个地运行。
    • 其实,我想我会把这个转移到另一个问题上,因为它现在与这个无关......
    猜你喜欢
    • 2020-01-29
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 2015-12-23
    • 2021-06-29
    • 2013-01-27
    • 2021-05-16
    • 2018-02-17
    相关资源
    最近更新 更多