Skip to content

Instantly share code, notes, and snippets.

@ckinmind
Last active December 12, 2017 11:21
Show Gist options
  • Save ckinmind/8d46219f554ae3a5df8a0e51051f571a to your computer and use it in GitHub Desktop.
Save ckinmind/8d46219f554ae3a5df8a0e51051f571a to your computer and use it in GitHub Desktop.
Line——animate line

说明

知识点

  • d3.active - 对于一个给定的节点选择活跃中的过渡
  • 关于start事件
<!doctype html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<title>Document</title>
<style>
.line {
fill: none;
stroke: #000;
stroke-width: 1.5px;
}
</style>
</head>
<body>
<svg width='900' height='500'></svg>
<script src='//d3js.org/d3.v4.min.js'></script>
<script>
const n = 40,
random = d3.randomNormal(0, 0.2), // d3.randomNormal - 正态分布
data = d3.range(n).map(random)
const svg = d3.select('svg'),
margin = {top: 20, right: 20, bottom: 20, left: 40},
width = +svg.attr('width') - margin.left - margin.right,
height = +svg.attr('height') - margin.top - margin.bottom,
g = svg.append('g').attr('transform', `translate(${margin.left}, ${margin.top})`)
const x = d3.scaleLinear().domain([0, n - 1]).range([0, width])
const y = d3.scaleLinear().domain([-1, 1]).range([height, 0])
const line = d3.line()
.x((d, i) => x(i))
.y((d, i) => y(d))
g.append('defs')
.append('clipPath')
.attr('id', 'clip')
.append('rect')
.attr('width', width)
.attr('height', height)
// 绘制x轴
g.append('g')
.attr('class', 'axis axis--x')
.attr('transform', `translate(0, ${y(0)})`)
.call(d3.axisBottom(x))
// 绘制y轴
g.append('g')
.attr('class', 'axis axis--y')
.call(d3.axisLeft(y))
// 定义一块clipPath去隐藏超出部分绑定事件
g.append('g')
.attr('clip-path', 'url(#clip)')
.append('path')
.datum(data)
.attr('class', 'line')
.transition()
.duration(500)
.ease(d3.easeLinear) //如果注释这句,则移动的过渡就会变得一顿一顿
.on('start', tick)
function tick() {
// 插入一个新值
data.push(random())
d3.select(this)
.attr('d', line)
.attr('transform', null)
// Slide it to the left.
d3.active(this) // d3.active - 对于一个给定的节点选择活跃中的过渡
.attr('transform', `translate(${x(-1)},0)`)
.transition()
.on('start', tick)
// 删除第一个数据
data.shift()
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment