前几天在群里面看到有人在问这个图怎么画, 正好当时有空, 就画了一个, 贴出来, 让需要的人能用一用
还是先上图吧
实现的效果是, 最右边的那个条条, 每秒高度自增1, 一分钟之后,整个界面右移一个条条的位置,最右边的一根删除,在最左边在加一根新的,继续自增,看代码
html部分
<!DOCTYPE html>
<meta charset="utf-8">
<title>Timeline</title>
<link type="text/css" rel="stylesheet" href="css/ha_timeline.css" />
<body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type="text/javascript" src="js/d3test2.js"></script>
<script type="text/javascript" src="js/lib/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
</script>
</body>
js部分
var dataset=[20,12,13,19,21,25,22,18,15,13,11,12];
var w = 500, h = 200, barPadding = 1, time=0;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var g1 = svg.append("g")
.attr("id", "g1");
var g2 = svg.append("g")
.attr("id", "g2")
g1.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d,i){return i*(w/dataset.length)})
.attr("y", function(d){return h-d})
.attr("width", w/dataset.length-barPadding)
.attr("height", function(d){return d})
.attr("fill", "rgb(223,240,248)");
g2.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d,i){return i*(w/dataset.length)})
.attr("y", function(d){return h-d})
.attr("width", w/dataset.length-barPadding)
.attr("height", 3)
.attr("fill", "rgb(118,170,194)");
function interval(){
dataset[dataset.length-1]+=2;
g1.selectAll("rect")
.data(dataset)
.transition()
.delay(200)
.duration(1000)
.ease("linear")
.attr("x", function(d,i){return i*(w/dataset.length)})
.attr("width", w/dataset.length-barPadding)
.attr("y", function(d){return h-d})
.attr("height", function(d){return d});
g2.selectAll("rect")
.data(dataset)
.transition()
.delay(200)
.duration(1000)
.ease("linear")
.attr("x", function(d,i){return i*(w/dataset.length)})
.attr("y", function(d){return h-d})
.attr("width", w/dataset.length-barPadding);
time++;
if(time >= 60){
time=0;
dataset.shift();
dataset.push(Math.round(Math.random()*50));
var g11=g1.selectAll("rect")
.data(dataset);
g11.exit()
.remove();
g11.enter()
.append("rect")
.attr("x", function(d,i){return i*(w/dataset.length)})
.attr("y", function(d){return h-d})
.attr("width", w/dataset.length-barPadding)
.attr("height", function(d){return d})
.attr("fill", "rgb(223,240,248)");
var g22=g2.selectAll("rect")
.data(dataset)
.transition();
g22.exit()
.remove();
g22.enter()
.append("rect")
.attr("x", function(d,i){return i*(w/dataset.length)})
.attr("y", function(d){return h-d})
.attr("width", w/dataset.length-barPadding)
.attr("height", 3)
.attr("fill", "rgb(118,170,194)");
}
}
setInterval("interval()", 1000);
点
我查看效果
![](http://my.oschina.net/js/ke/plugins/emoticons/images/13.gif)