用d3.js 画两条line,x轴为24小时,每3个小时为一格,有连线动画效果,两秒内把linel连成功
时间: 2024-02-18 17:05:09 浏览: 28
好的,下面是一个用d3.js画两条line,x轴为24小时,每3个小时为一格,有连线动画效果,两秒内把line1连成功的示例代码:
```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: 0, y: 30},
{x: 3, y: 50},
{x: 6, y: 80},
{x: 9, y: 70},
{x: 12, y: 60},
{x: 15, y: 40},
{x: 18, y: 80},
{x: 21, y: 30},
];
var data2 = [
{x: 0, y: 70},
{x: 3, y: 50},
{x: 6, y: 20},
{x: 9, y: 30},
{x: 12, y: 40},
{x: 15, y: 60},
{x: 18, y: 20},
{x: 21, y: 70},
];
// 定义画布和线段
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();
line1.attr("stroke-dasharray", totalLength1 + " " + totalLength1)
.attr("stroke-dashoffset", totalLength1)
.transition()
.duration(2000)
.ease(d3.easeLinear)
.attr("stroke-dashoffset", 0);
}
// 调用动画函数
animate();
</script>
</body>
</html>
```
在这个示例中,我们首先定义了两条线段的数据 `data1` 和 `data2`,其中 `x` 坐标表示小时数,每 3 个小时为一格。接着,我们使用 `d3.select()` 方法选择 SVG 元素,并分别添加两条路径元素 `line1` 和 `line2`。接着,我们定义了一个名为 `animate()` 的动画函数,该函数使用 `getTotalLength()` 方法获取第一条线段的总长度,并使用 `attr()` 方法设置 `stroke-dasharray` 和 `stroke-dashoffset` 属性,从而实现路径动画效果。最后,我们在脚本末尾调用动画函数以启动动画效果。
希望这个示例能够帮助你实现你的需求!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)