javascript - 如何在页面上的网页元素之间绘制连接线

标签 javascript html css reactjs svg

我想找到最简单的准系统(也就是说,如果可能的话,没有库;这是一个学习练习)在组件之间画一条简单的线。 The elements are divs representing cards always stacked vertically可能永远。卡片可以有不同的高度。该线将从任何给定元素的左侧退出(卡片 a),转 90 度并上升,转 90 度回到另一个元素(卡片 b)。

Example

我已经尝试了一些东西。我还没有完全工作,他们看起来都需要一些认真的时间来弄清楚他们。我想知道的是什么是正确/首选的方法来做这件事,这样我就可以把时间花在正确的事情上,并且它是 future 的观点:

  1. 我可以在任意两个框之间添加任意数量的连接线,而不仅仅是连续的框
  2. 这些行服从卡片的大小调整和上下滚动
  3. 有些卡片可能没有终点,而是终止于页面左上角,等待它们的卡片滚动到 View 中或被创建。

尝试

我的第一个想法是在左侧的完整列组件中使用 ,但是将 Canvas 和其中的绘图与我的 div 对齐很痛苦,因为以及无限滚动的 Canvas 。无法让它工作。

接下来我尝试了

s。喜欢McBrackets做了here .为 div 的顶部、底部和外边缘着色,并将其与相关的两张卡片对齐,但虽然我可以相对于卡片 a 定位它,但我不知道如何将其停在卡片 b 处。

最后我尝试了 s。只需 .getElementById() 然后添加遵循上述说明的 SVG 路径。即

    const connectingPath =
        "M " + aRect.left + " " + aRect.top + " " +
        "H " + (aRect.left - 50) +
        "V " + (bRect.top) +
        "H " + (bRect.left);

似乎没有任何问题,事实证明它很难调试,而且它看起来像是一个更复杂的解决方案,因为我需要考虑调整大小等等。

最佳答案

您可以通过对要连接的盒子进行一些测量来应用类似的东西; offsetTopclientHeight


更新添加了一些未抽牌要求的逻辑。

虽然这不能完全模拟卡片的动态填充,但我进行了更新以展示如何处理只绘制一张卡片的场景。

  1. 单击使用默认值(1 和 5)连接。这将从框 1 开始显示一个打开的连接器。
  2. 单击“添加框 5”。这将添加丢失的框并更新连接器。

这里剩下的工作是在 scroll 上创建一个事件监听器以检查连接器列表。从那里您可以检查两个框是否出现在 DOM 中(请参阅 checkConnectors 函数)。如果它们出现,则将值传递给 addConnector,这将完全连接它们。

const connectButton = document.getElementById("connect");
const container = document.getElementById("container");
const error = document.getElementById("error");
const addBoxButton = document.getElementById("addBox");

const connectors = new Map();

const getMidpoint = element => element.offsetTop + element.clientHeight / 2;
const getElementAtBoxId = id => document.getElementById(`box${id}`);

connectButton.addEventListener("click", () => {
  const firstBoxId = document.getElementById("selectFirstBox").value;
  const secondBoxId = document.getElementById("selectSecondBox").value;

  if (firstBoxId === null && secondBoxId === null) return;

  error.style.display = firstBoxId === secondBoxId ? "block" : "none";
  
  if (firstBoxId === secondBoxId) return;

  const firstInput = getElementAtBoxId(firstBoxId);
  const secondInput = getElementAtBoxId(secondBoxId);

  // Check for undrawn cards
  if (firstInput && !secondInput || !firstInput && secondInput) {
    addConnector(firstBoxId, firstInput, secondBoxId, secondInput, true);
    return;
  }
  
  const firstBox = firstInput.offsetTop < secondInput.offsetTop ? firstInput : secondInput;
  const secondBox = firstInput.offsetTop < secondInput.offsetTop ? secondInput : firstInput;

  addConnector(firstBoxId, firstBox, secondBoxId, secondBox);
});

function addConnector(firstBoxId, firstBox, secondBoxId, secondBox, half = false) {
  const args = { firstBoxId, firstBox, secondBoxId, secondBox, half };
  if (!firstBox && !secondBox) throw new Error(`Invalid params: ${JSON.stringify(args)}`);
  
  const connectorId = `${firstBoxId}:${secondBoxId}`;  
  let connector, color;

  if (connectors.has(connectorId)) color = connectors.get(connectorId).color;
  else color = '#' + Math.floor(Math.random() * 16777215).toString(16);
  
  if (half) {
    const box = firstBox ? firstBox : secondBox;
    // if firstBox draw up else draw down
    if (firstBox) {
      connector = buildConnector(getMidpoint(box), box.parentElement.clientHeight);
      connector.style.borderBottom = "unset";
    } else {
      // similar logic for draw up
    }
  } else {
    connector = buildConnector(getMidpoint(firstBox), getMidpoint(secondBox));
  }
  
  connector.style.borderColor = color;
  
  container.appendChild(connector);
  connectors.set(connectorId, { ...args, color });
}

function buildConnector(height1, height2) {
  const connector = document.createElement("div");
  
  connector.classList.add("connector");
  connector.style.top = `${height1}px`;
  connector.style.height = `${Math.abs(height2 - height1)}px`;
  
  return connector;
}

window.addEventListener("resize", () => {
  for (const connector of connectors.values()) {
    const { firstBoxId, firstBox, secondBoxId, secondBox, half } = connector;
    if(firstBox || secondBox) {
      addConnector(firstBoxId, firstBox, secondBoxId, secondBox, half);
      console.log(`resize detected, adjusting connector between ${firstBoxId} and ${secondBoxId}`);
    }
  }
});

addBoxButton.addEventListener("click", () => {
  const box = document.createElement("div");
  box.innerText = 5;
  box.id = "box5";
  box.classList.add("box");
  container.appendChild(box);
  
  addBoxButton.style.display = 'none';
  
  // check if connectors need to be updated
  checkConnectors();
});
  
function checkConnectors() {
  for (const connector of connectors.values()) {
    if (connector.half) {
      let { firstBox, firstBoxId, secondBox, secondBoxId } = connector;

      firstBox = firstBox ? firstBox : getElementAtBoxId(firstBoxId);
      secondBox = secondBox ? secondBox : getElementAtBoxId(secondBoxId);
  
      // both boxes in DOM -> update connector
      if (firstBox && secondBox) {
        addConnector(firstBoxId, firstBox, secondBoxId, secondBox);
      }
    }
  }
}
.box {
  border: solid 1px;
  width: 60px;
  margin-left: 30px;
  margin-bottom: 5px;
  text-align: center;
}

#inputs {
  margin-top: 20px;
}

#inputs input {
  width: 150px;
}

.connector {
  position: absolute;
  border-top: solid 1px;
  border-left: solid 1px;
  border-bottom: solid 1px;
  width: 29px;
}

#error {
  display: none;
  color: red;
}
<div id="container">
  <div id="box1" class="box">1</div>
  <div id="box2" class="box">2</div>
  <div id="box3" class="box">3</div>
  <div id="box4" class="box">4</div>
</div>
<div id="inputs">
  <input id="selectFirstBox" type="number" placeholder="Provide first box id" min="1" value="1" max="5" />
  <input id="selectSecondBox" type="number" placeholder="Provide second box id" min="1" value="5" max="5" />
  <div id="error">Please select different boxes to connect.</div>
</div>
<button id="connect">Connect</button>
<button id="addBox">Add box 5</button>

关于javascript - 如何在页面上的网页元素之间绘制连接线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70623681/

相关文章:

javascript - Angular 5 View 子引用在 Safari 中不起作用(v 11.1)

javascript - Codeigniter 上的 AutoSuggest (Ajax) - 404 错误

html - 在CSS中,html标签和类名之间的空格是否意味着样式应用于该标签内的任何元素?

html - 使用 Bootstrap Grid 的语义标记

html - Flex 元素不需要是 Flex 容器内的显式元素吗?

javascript - 使用类型模块访问脚本标记中定义的变量?

javascript - 在计算机上打开链接的新选项卡,但在移动设备上则不打开

html - 自定义、常规、有序的元素符号列表样式

Javascript:在 JS 中创建的具有属性的元素未被函数读取

javascript - 创建一个可访问的列表,其中每个 li 元素内部都有一些复杂的内容