2016-08-18 69 views
4

比如我有一个过渡:获得预期的属性值

var sel = container.selectAll('div') 
    .transition() 
    .duration(1000) 
    .attr('transform', 'translate(100,500)'); 

在某个时刻,我需要知道的一些内容的土地上,例如中

setTimeout(() => { 
    var value = d3.select('div#target') 
     .expectedAttr('transform'); 
    assertEqual(value, 'translate(100,500)'); 
}, 500); 

在D3中是否有像这样的内置功能?否则,我将不得不通过d3.transition().attr()方法来存储传递给它的值。

编辑

我发现,D3上创建元素__transition__场,这似乎包含有关过渡的信息,但我看不出有什么办法找到一个目标属性值存在。

+0

*您期望的含义* value:转换仍在运行时的特定时刻的值还是其转换的目标值? – altocumulus

+0

@altocumulus对,我需要知道元素在转换结束时所具有的属性的值。也许它存储在某个字段中,例如数据绑定的'__data__'字段。 –

回答

5

起初我以为这是不可能的,因为目标值似乎被闭包隐藏起来。尽管有一点小技巧,但这个值可以被检索出来。

你要记住,调用transition.attr()时,D3将执行以下操作:

对于每个选定的元素,创建具有指定名称到指定的目标值属性的attribute tween

这个自动创建的补间可以通过调用transition.attrTween(attrName)来访问。

当此补间被D3调用时,它将返回interpolator。这又可以访问创建插补器时关闭的目标值。当进一步向下读取的文档的实际伎俩变得很明显:

返回然后内插器被调用用于过渡的每个帧中,为了,正在传递的缓和时间,典型地在范围[0, 1]。

明知对于t –在过渡–的结束时的最终值将是1 ,可以调用先前获得的内插器使用此值,这将产生的过渡的目标值。

var targetValue = transition 
    .attrTween("x2")   // Get the tween for the desired attribute 
    .call(line.node())   // Call the tween to get the interpolator 
    (1);      // Call the interpolator with 1 to get the target value 

以下示例通过打印已运行转换的目标值来显示此内容。

var line = d3.select("line"); 
 
line 
 
    .transition() 
 
    .duration(2000) 
 
    .attr("x2", 100); 
 
    
 
setTimeout(function() { 
 
    var transition = d3.active(line.node()) // Get the active transition on the line 
 
    var targetValue = transition 
 
    .attrTween("x2")      // Get the tween for the desired attribute 
 
    .call(line.node())      // Call the tween to get the interpolator 
 
    (1);         // Call the interpolator with 1 to get the target value 
 
    console.log(targetValue);    // 100 
 
}, 1000);
<script src="https://d3js.org/d3.v4.js"></script> 
 

 
<svg><line x2="0" y2="100" stroke="black"></line></svg>

这同样适用于风格转换,你会用transition.styleTween()得到真正的补间。

+0

太棒了! D3 v3有解决方案吗? –

+1

@AlexanderShutov使用D3 v3的唯一问题是获取元素上的活动转换,即调用v4引入的'd3.active()'。看看[*“什么是获取给定元素的活动(运行中)D3 v3转换的标准方式?”*](/ q/13844179)进行讨论。两种方法都有其缺点和限制,但根据代码的其余部分,这可能是合适的。 – altocumulus