D3.js 动画 过渡效果 (V3版本)
1 var width = 600;
2 var height = 400;
3
4 var svg = d3.select("#body")
5 .append("svg")
6 .attr("width",width)
7 .attr("height",height)
8
9 svg.append("rect")
10 .attr("fill","yellow")
11 .attr("x",100)
12 .attr("y",100)
13 .attr("width",100)
14 .attr("height",30)
15 .transition()
16 .attr("width",300)
1 var rect = svg.append("rect")
2 .attr("fill","yellow")
3 .attr("x",100)
4 .attr("y",100)
5 .attr("width",100)
6 .attr("height",30)
7
8 //打印rect
9 console.log(rect) //rect是选择集
10
11 //启动过渡效果
12 var rectTran = rect.transition()
13
14 //打印rectTran
15 console.log(rectTran) //rectTran是一个过渡对象
1 var rect = svg.append("rect")
2 .attr("fill","yellow")
3 .attr("x",100)
4 .attr("y",100)
5 .attr("width",100)
6 .attr("height",30)
7 var rectTran = rect.transition()
8 .delay(500) //延迟500ms再开始
9 .duration(1000) //过渡时长为1000ms
10 .ease("blunce") //过渡样式
11 .attr("width",300) //目标属性
1 var rect = svg.append("rect")
2 .attr("fill","yellow")
3 .attr("x",100)
4 .attr("y",100)
5 .attr("width",100)
6 .attr("height",30)
7
8
9 var rectTran = rect.transition() //开始一个过渡
10 .attr("width",300) //目标宽度为300
11 .transition() //开始一个过渡
12 .attr("height",300) //目标高度为300
13 .transition() //开始一个过渡
14 .attr("width",100) //目标宽度为100
15 .transition() //开始一个过渡
16 .attr("height",100) //目标高度为100
1 .attr("width",100)
2 .transition()
3 .attr("width",300)
1 var rect = svg.append("rect")
2 .attr("fill","yellow")
3 .attr("x",100)
4 .attr("y",100)
5 .attr("width",100)
6 .attr("height",30)
7
8 var rectTran = rect.transition()
9 .duration(2000)
10 .attrTween("width",function(d,i,a){
11 return function(t){
12 return Number(a) + t * 300
13 }
14 })
1 svg.append("rect")
2 .attr("fill","yellow")
3 .attr("x",100)
4 .attr("y",100)
5 .attr("width",100)
6 .attr("height",30)
7 .transition()
8 .duration(2000)
9 .attr("fill",'red')
1 svg.append("rect")
2 .attr("fill","yellow")
3 .attr("x",100)
4 .attr("y",100)
5 .attr("width",100)
6 .attr("height",30)
7 .transition()
8 .duration(2000)
9 .attr("width",300)
10
11 var text = svg.append("text")
12 .attr("fill","white")
13 .attr("x",150)
14 .attr("y",100)
15 .attr("dy","1.2em")
16 .attr("text-anchor","end")
17 .text(100)
18
19
20 var initx = text.attr("x")
21 var initText = text.text()
22
23 var textTran = text.transition()
24 .duration(2000)
25 .tween("text",function(){
26 return function(t){
27 d3.select(this)
28 .attr("x",Number(initx) + t * 250 )
29 .text(Math.floor(Number(initText) + t * 300 ))
30 }
31 })
1 //当t为0时,函数体力的操作是:
2 d3.select(this)
3 .attr("x",150 + 0 * 250)
4 .text(Math.floor(100 + 0 * 300))
5
6 //当t为1时,函数体里的操作是:
7 d3.select(this)
8 .attr("x",150 + 1 * 250 )
9 .text(Math.floor(100 + 1 * 300))
1 var rect = svg.append("rect")
2 .attr("fill","yellow")
3 .attr("x",100)
4 .attr("y",100)
5 .attr("width",100)
6 .attr("height",30)
7
8 rect.transition()
9 .attr("width",0)
10 .remove()