2017-01-16 4 views
3

私は、スライドするx軸を持つd3を使ってグラフを実装しています。 Demod3 v4でトランジションの再生を修正するにはどうすればよいですか?

問題は、別のタブに変更して戻ったとき(たとえば10秒後)に、d3が欠落したトランジションを再生しようとしているように見えて、軸の動作が非常に面倒です。 hereを参照してください。

マイク・ボストックmentions that

D3 4.0フィックス時間の定義を変更することでこの問題。遷移は通常、絶対時間と同期する必要はありません。トランジションは、ビュー全体でオブジェクトを追跡するための主な知覚支援ツールです。したがって、D3 4.0は、認識された時間に実行されます。これは、ページがフォアグラウンドにある場合にのみ前進します。タブがバックグラウンドにされ、フォアグラウンドに戻されると、何も起こっていなかったかのように単に取り上げられます。

これは本当に修正されていますか?私は間違って何かしていますか?

const timeWindow = 10000; 
 
const transitionDuration = 3000; 
 

 
const xScaleDomain = (now = new Date()) => 
 
    [now - timeWindow, now]; 
 

 
const totalWidth = 500; 
 
const totalHeight = 200; 
 
const margin = { 
 
    top: 30, 
 
    right: 50, 
 
    bottom: 30, 
 
    left: 50 
 
}; 
 
const width = totalWidth - margin.left - margin.right; 
 
const height = totalHeight - margin.top - margin.bottom; 
 

 
const svg = d3.select('.chart') 
 
    .append('svg') 
 
    .attr('width', totalWidth) 
 
    .attr('height', totalHeight) 
 
    .append('g') 
 
    .attr('transform', `translate(${margin.left}, ${margin.top})`) 
 

 
svg 
 
    .append('rect') 
 
    .attr('width', width) 
 
    .attr('height', height); 
 

 
// Add x axis 
 
const xScale = d3.scaleTime() 
 
    .domain(xScaleDomain(new Date() - transitionDuration)) 
 
    .range([0, width]); 
 

 
const xAxis = d3.axisBottom(xScale); 
 

 
const xAxisSelection = svg 
 
    .append('g') 
 
    .attr('transform', `translate(0, ${height})`) 
 
    .call(xAxis); 
 

 
// Animate 
 
const animate =() => { 
 
    xScale.domain(xScaleDomain()); 
 

 
    xAxisSelection 
 
    .transition() 
 
    .duration(transitionDuration) 
 
    .ease(d3.easeLinear) 
 
    .call(xAxis) 
 
    .on('end', animate); 
 
}; 
 

 
animate();
svg { 
 
    margin: 30px; 
 
    background-color: #ccc; 
 
} 
 

 
rect { 
 
    fill: #fff; 
 
    outline: 1px dashed #ddd; 
 
}
<script src="https://unpkg.com/[email protected]/build/d3.js"></script> 
 
<div class="chart"></div>

答えて

1

問題はD3遷移ではありません。ここの問題はnew Date()です。

別のタブに移動するたびに、移行が一時停止します。ここまでは順調ですね。しかし、あなたはのは言わせて、チャートに戻ってきたときに、20秒後、あなたは現在の日付の新しい日付を取得...しかし、あなたのtimeWindowは同じであるだけでなく、あなたのtransitionDuration

ます
const timeWindow = 10000; 
const transitionDuration = 3000; 

const xScaleDomain = (now = new Date()) => [now - timeWindow, now]; 

ドメインの任意のポイントでの古い値と新しい値の差がもう3秒ではないため、軸が先に高速にジャンプします。

これは非常に単純な解決策です。問題はnew Date()であることを示すために、粗すぎて改善が必要です。このソリューション(再び、これまで完璧から)で、私は手動に関係なく、あなたが別のタブに滞在する時間を、10秒をジャンプしないように、それぞれのアニメーションに日付を設定します。ここでは

var t = xScale.domain()[1]; 
t.setSeconds(t.getSeconds() + 10); 

xScale.domain([xScale.domain()[1], t]); 

CodePenです:http://codepen.io/anon/pen/GrjMxy?editors=0010

あなたのコードを使用して

よりよい解決策は、(つまり、ユーザーが別のタブになっている時間、である)考慮new Date()新旧new Date()間の差を取ることtimeWindowtransitionDurationを変更することになります。

+0

ありがとうございます!意味あり。 d3は「遷移の一時停止」と「遷移の再開」のフックを提供するので、時間差を測定できますか? –

+0

私の頭の上からは、ネイティブではないと思うが、あなた自身の機能を作ることができる。 –

関連する問題