2016-08-18 98 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