用d3.js 画两条line,并添加动画连线效果
时间: 2024-02-18 10:05:03 浏览: 32
好的,下面是一个用d3.js画两条line并添加动画连线效果的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3.js Line Animation Example</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<svg width="500" height="300"></svg>
<script>
// 定义数据
var data1 = [{x: 50, y: 50}, {x: 150, y: 150}, {x: 250, y: 100}, {x: 350, y: 200}];
var data2 = [{x: 50, y: 200}, {x: 150, y: 100}, {x: 250, y: 150}, {x: 350, y: 50}];
// 定义画布和线段
var svg = d3.select("svg");
var line1 = svg.append("path").datum(data1)
.attr("fill", "none")
.attr("stroke", "red")
.attr("stroke-width", 2);
var line2 = svg.append("path").datum(data2)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 2);
// 定义动画函数
function animate() {
var totalLength1 = line1.node().getTotalLength();
var totalLength2 = line2.node().getTotalLength();
line1.attr("stroke-dasharray", totalLength1 + " " + totalLength1)
.attr("stroke-dashoffset", totalLength1)
.transition()
.duration(2000)
.ease(d3.easeLinear)
.attr("stroke-dashoffset", 0);
line2.attr("stroke-dasharray", totalLength2 + " " + totalLength2)
.attr("stroke-dashoffset", totalLength2)
.transition()
.duration(2000)
.ease(d3.easeLinear)
.attr("stroke-dashoffset", 0);
}
// 调用动画函数
animate();
</script>
</body>
</html>
```
在这个示例中,我们首先定义了两条线段的数据 `data1` 和 `data2`,然后使用 `d3.select()` 方法选择 SVG 元素,并分别添加两条路径元素 `line1` 和 `line2`。接着,我们定义了一个名为 `animate()` 的动画函数,该函数使用 `getTotalLength()` 方法获取每条线段的总长度,并使用 `attr()` 方法设置 `stroke-dasharray` 和 `stroke-dashoffset` 属性,从而实现路径动画效果。最后,我们在脚本末尾调用动画函数以启动动画效果。
希望这个示例能够帮助你实现你的需求!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)