- 图表类型:折线图
- 原图地址:Animate path in D3
- path动画
stroke-dashoffset
属性指定了dash模式到路径开始的距离Element.getTotalLength()
以像素为单位,返回路径的长度(仅适用于path元素)stroke-dasharray
属性stroke-dasharray可控制用来描边的点划线的图案范式作为一个外观属性,它也可以直接用作一个CSS样式表内部的属性
stroke-dashoffset
属性指定了dash模式到路径开始的距离Element.getTotalLength()
以像素为单位,返回路径的长度(仅适用于path元素)stroke-dasharray
属性stroke-dasharray可控制用来描边的点划线的图案范式作为一个外观属性,它也可以直接用作一个CSS样式表内部的属性<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv='Content-Type' content='text/htmlcharset=utf-8'/> | |
<style type='text/css'> | |
#line{ | |
width: 100%; | |
margin: 20px 0; | |
height: 300px; | |
} | |
.old { | |
stroke: lightgrey; | |
stroke-dasharray: 5,2; | |
stroke-dashoffset: 5; | |
} | |
</style> | |
</head> | |
<body> | |
<div id='line'></div> | |
<script src='https://d3js.org/d3.v4.min.js'></script> | |
<script type='text/javascript'> | |
const w = 900 | |
const h = 400 | |
const svg = d3.select('#line') | |
.append('svg') | |
.attr('width', w) | |
.attr('height', h) | |
.attr('id', 'visualization') | |
const x = d3.scaleLinear().domain([0, 10]).range([0, w]) | |
const y = d3.scaleLinear().domain([0, 10]).range([10, h - 10]) | |
const line = d3.line() | |
.x((d,i) => x(i)) | |
.y(d => y(d)) | |
.curve(d3.curveNatural) | |
let repeat = () => { | |
//随机生成line的数据 | |
const data = d3.range(11).map(() => Math.random() * 10) | |
svg.selectAll('path').attr('class', 'old') | |
const path = svg.append('path') | |
.attr('d', line(data)) | |
.attr('stroke', 'darkgrey') | |
.attr('stroke-width', 2) | |
.attr('fill', 'none') | |
// Element.getTotalLength() 以像素为单位,返回路径的长度(仅适用于path元素) | |
const totalLength = path.node().getTotalLength() | |
path | |
.attr('stroke-dasharray', totalLength + ' ' + totalLength) | |
.attr('stroke-dashoffset', totalLength) | |
.transition() | |
.duration(4000) | |
.ease(d3.easeLinear) | |
.attr('stroke-dashoffset', 0) | |
.on('end', repeat) | |
} | |
repeat() | |
</script> | |
</body> | |
</html> |