javascript - SVG 路径元素 .transition() - 添加到哪里?

标签 javascript svg d3.js transition

基本上,我希望我的图表从 x 轴开始,并在两秒内增长到实际数据值。这可能是一件简单的事情,但我似乎无法让它发挥作用。

我正在附加一个区域元素,其中 d=""属性是由一个函数(区域)构建的,我不确定在何处添加过渡。

首先我想在区域函数中执行此操作,但失败了。当添加区域元素但没有成功时,我也尝试过这样做。

这是我的代码:

// Create the area element for each object - a function that will be passed to "path"
var area = d3.svg.area()
    .x(function(d) { return x(d.year); })
    .y0(height)
    //.y1(height)
    //.transition()
    //.duration(2000)
    .y1(function(d) { return y(d.average); });

// build the container SVG element
var svg = d3.select("#co2").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

svg.append("path") 
    // pull in data to the path 
    .datum(data)
    .attr("class", "area")
    // passing in the area function, for each object
    .attr("d", area)
    // starts the graph opacity at 0 and fades to 1 over 2.5 seconds
    .style("fill-opacity", "0")
    .transition()
    .duration(2500)
    .style("fill-opacity", "1");

最佳答案

与其尝试在面积图的形状上使用过渡,不如对要设置动画的整个 svg 元素应用 scale(x,y) 变换。这种方法的优点是它不限于特定的渲染实现(例如:不是特定于路径/d3.area)。

不过有几个陷阱需要注意:

  • 为避免 transition() 行为,处理边距调整,确保您有一个单独的“g”元素供 transition() 转换作用于

  • SVG原点(0,0)在左上角,所以除了缩放SVG区域外,还需要设置图形的底数

综合如下:

'g' 元素:

var svg = d3.select("#co2").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
      .attr("transform", "translate(" + margin.left, "," + margin.top + ")")
    // define a new 'g' to scope the transition, and keep separate from the margin adjusting transform above
    .append("g"); 

transition() 包括基础调整:

svg
  .attr("transform", "translate(0," + height + ") scale(1, 0)")
.transition().duration(2000)
  .attr("transform", "translate(0,0) scale(1, 1)");

一如既往,这最好用完整的例子来说明:http://bl.ocks.org/4239516

关于javascript - SVG 路径元素 .transition() - 添加到哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13772325/

相关文章:

javascript - 如何在页面刷新后保持按钮处于事件状态?

html - 在悬停时更改 css background-image svg 绘制行为?

javascript - Angular JS 错误 - http ://errors. angularjs.org/1.5.0/$injector/unpr?p0

javascript - 如何在html onclick中调用类函数

WordPress 和 SVG

javascript - d3 弧抛出错误中的 padAngle 函数

javascript - D3 - 每 2 秒更新条形图

javascript - 如何隐藏条形图轴的线条?

javascript - 使用 Q 用异步调用填充数组

javascript - SVG 路径渲染是否可以在 geometricPrecision 选项之外消除锯齿?