2012-11-15 42 views
3

我想實現如圖所示here一個簡單的路徑轉換。我不是JavaScript的,也不D3魔法師,所以我想給我最好的拍攝:簡單路徑切換

var line = d3.svg.line() 
    .x(function(d) { return x(d.date); }) 
    .y(function(d) { return y(d.price); }); 

svg.append("path") 
    .datum(data) 
    .attr("class", "line") 
    .attr("d", line) 
    .transition().duration(next.duration||1000).delay(next.delay||0); # not right 

我如何過渡到正常工作?

+0

參見http://stackoverflow.com/questions/14275249/how-can-i-animate-a-progressive-drawing-of-svg-path/14282391#14282391 – Phrogz

回答

11

一種方式做路徑繪圖動畫D3是使用破折號陣列和衝偏移屬性。

你可以做的是設置dashoffset總路徑長度,則減少dashoffset隨着時間的推移,直到爲零。這將模擬正在繪製的路徑。檢查出stroke-dasharraystroke-dashoffset的SVG文檔。

從概念上講,你在做什麼是這樣的:

說你的線是4個單位長度(----)。您將dasharray設置爲(---- ,,,,),即四個單位,然後是四個空格。您將折線偏移設置爲4個單位,因此該線將位於可見空間左側的4個單位。然後,您降低dashoffset爲0,行會看起來像( - ,,,,),然後( - ,,,)等,直到整個線路繪製。

var line = d3.svg.line() 
.x(function(d) { return x(d.date); }) 
.y(function(d) { return y(d.price); }); 

var path = svg.append("path") 
        .attr("d", line(data)) 
        .classed("line", true); 

var pathLength= path.node().getTotalLength(); 

path 
    .attr("stroke-dasharray", pathLength + " " + pathLength) 
    .attr("stroke-dashoffset", pathLength) 
    .transition() 
    .duration(2000) 
    .ease("linear") 
    .attr("stroke-dashoffset", 0); 

-

Duopixel's得知後here