[英]how to make smooth transitions with d3 + socket.io
我有一個d3.js樹形圖,每次服務器發出更新時都會對其執行ping操作。 更新來自Twitter流。 有很多更新。 因此,樹形圖的動畫非常生澀,因為在1500毫秒過渡完成之前,樹形圖已多次更新。
是否可以將更新節點值的代碼與更新視圖的代碼分開? 我希望找到一個解決方案,該解決方案將不斷更新樹形圖的值,但僅每1500-2000ms更新一次視圖。
請查看我完整的d3腳本 :
var socket = io.connect();
var margin = {top: 40, right: 10, bottom: 10, left: 10},
width = 1000 - margin.left - margin.right,
height = 650 - margin.top - margin.bottom;
var color = d3.scale.category20c();
var treemap = d3.layout.treemap()
.size([width, height])
.sticky(false)
.value(function(d) { return d.size; });
var div = d3.select("body").append("div")
.style("position", "relative")
.style("width", (width + margin.left + margin.right) + "px")
.style("height", (height + margin.top + margin.bottom) + "px")
.style("left", margin.left + "px")
.style("top", margin.top + "px");
var root;
socket.on('update', function(stream) {
console.log('tweets')
div.datum(root).selectAll(".node").remove();
root = stream.masterlist;
var node = div.datum(root).selectAll(".node")
.data(treemap.nodes)
.enter().append("div")
.attr("class", "node")
.call(position)
.style("background", function(d) { return d.children ? color(d.name) : null; })
.text(function(d) { return d.children ? null : d.name; });
d3.selectAll("input").on("change", function change() {
var value = this.value === "count"
? function() { return 1; }
: function(d) { return d.size; };
node
.data(treemap.value(value).nodes)
.transition()
.duration(1500)
.call(position);
});
});
function position() {
this.style("left", function(d) { return d.x + "px"; })
.style("top", function(d) { return d.y + "px"; })
.style("width", function(d) { return Math.max(0, d.dx - 1) + "px"; })
.style("height", function(d) { return Math.max(0, d.dy - 1) + "px"; });
}
這段代碼取自出色的bl.ocks.org網站上的樹圖示例 ,僅作了細微的更改(我的數據來自回調而不是json)。 我試圖在socket.on()
setInterval()
外部使用setInterval()
從視圖邏輯中拆分值邏輯,但是我的嘗試要么無法減慢轉換速度,要么就完全破壞了樹形圖。
d3.selectAll("input").on("change", function change() {
var value = this.value === "count"
? function() { return 1; }
: function(d) { return d.size; };
});
}); // end socket.on();
setInterval(function() {
node
.data(treemap.value(value).nodes)
.transition()
.duration(1500)
.call(position);
}, 2000);
非常感謝您的見解!
您要執行的操作稱為反跳。 有幾個javascript庫可供您使用(我使用下划線)。 您也可以自己寫一個。 我在博客文章中找到了這個:
function debounce(fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
一旦實現或竊取了防抖動功能,其余的操作就很容易了:您只需用防抖動來包裝處理更新的函數:
socket.on('update', debounce(function(stream) {
console.log('tweets')
...
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.