d3 实现24小时时序图

D3.js实现24小时时序图与异常提示
本文通过D3.js库详细讲解如何绘制24小时时序图,并介绍如何在图中添加异常节点的提示功能,帮助理解数据状态。

d3 画圆点 实现24小时时序图并增加异常节点的提示功能

效果图

<!DOCTYPE html>
<html>

<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <style>
    body {
      text-align: center;
    }
    #svg_tooltip {
      position: absolute;
      border-radius: 4px;
      padding: 10px;
      z-index: 2000;
      font-size: 12px;
      line-height: 1.2;
      min-width: 10px;
      background: #000;
      color: #fff;
    }
    #svg_tooltip:before {
      content: "";
      position: absolute;
      display: block;
      width: 0px;
      border: 6px solid transparent;
      border-top: 6px solid #000;
      left: 45px;
      top: 34px;
    }
  </style>
</head>

<body>
  <h1>24小时状态时序图 d3</h1>
  <svg id="svg" width="310" height="38" style="background: #fff;border:1px solid #ccc;"></svg>
  <!-- 引入组件库 -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.js"></script>
  <script>
    let toolTip = d3.select("body")
      .append("div")
      .attr("id", "svg_tooltip")
      .style("position", "absolute")
      .style("pointer-events", "none")
      .style("display", "none")
      .style("z-index", 1006); // 要比全屏后的z-index 还高

    let arr = new Array(48).fill(2).fill(1, 20, 22).fill(0, 40, 48)
     console.log(arr, 'arr')

     arr.forEach((item, index) => {
      let c = d3.select("#svg").append("circle").attr("r", 3)
      if (index >= 32) {
        c.attr("cx", 6 + (index + 2) * 6)
      } else if (index >= 16) {
        c.attr("cx", 6 + (index + 1) * 6)
      } else {
        c.attr("cx", 6 + index * 6)
      }
      c.attr("cy", 19)
      let color = ""
      if (item === 2) {
        color = "#33ca6b"
      } else if (item === 1) {
        color = "#fe6e53"
      } else if (item === 0) {
        color = "#b9c8cf"
      }
      c.attr("fill", color)

      // 异常的节点 增加 监听事件
      if (item === 1) {
        c.on("mousemove", ($event) => {
          c.style("cursor", "pointer")
          let h = Math.floor(index / 2)
          let tiptxt = ""
          if (index % 2 === 1) {
            tiptxt = `${h}:30 -- ${h + 1}:00`
          } else {
            tiptxt = `${h}:00 -- ${h}:30`
          }
          toolTip.style("display", "block")
            .html(tiptxt)
            .style("left", $event.pageX - 50 + "px")
            .style("top", $event.pageY - 50 + "px")
        })

        c.on("mouseout", ($event) => {
          toolTip.style("display", "none")
        })
      }
    })
  </script>

</body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值