如何在 html 中画很多线?

How to draw lots of lines in html?

我的页面中有很多图像,我正在寻找一种方法来画一条线,将一个图像连接到另一个图像(它不一定是箭头,只是一条普通线。)。例如,让我们将 ($) 视为图像:

$

   $

现在我怎样才能用一条线连接这 2 个图像 ($)?

谢谢!

  1. div 标签:具有背景色、宽度、高度、变换:旋转(50 度)和良好定位属性
  2. SVG 标签
  3. PNG 图片
  4. Canvas

由于您似乎在询问基本的 JavaScript、HTML 和 CSS,这里有一个仅使用这些的简单方法。很高兴了解进行这些图形计算而不是完全依赖库背后的数学和理论。

通过计算两个图像之间的距离和角度,使用HTML div作为一条线。

// Get the position of the first image
var imgOnePosition = document.getElementById("one").getBoundingClientRect();

// Get the position of the second image
var imgTwoPosition = document.getElementById("two").getBoundingClientRect();

// Calculate the angle between the two images' positions.
// Math.atan2() returns a value in radians so convert it to degrees as well
var angle = Math.atan2(imgOnePosition.top - imgTwoPosition.top, imgOnePosition.left - imgTwoPosition.left) * (180 / Math.PI);

// Calculate the distance, hopefully you remember this from basic algebra :)
var distance = Math.sqrt(Math.pow(imgOnePosition.top - imgTwoPosition.top, 2) + Math.pow(imgOnePosition.left - imgTwoPosition.left, 2));

// Create a new DIV to represent our line
var line = document.createElement("div");

// Now we style it
line.style.position = "absolute"; // so that we can change left and top
line.style.width = distance + "px";
line.style.height = "2px";
line.style.left = "50%"; // Center the element in its parent
line.style.top = "50%"; // Center the element in its parent
line.style.background = "#000";
line.style.transformOrigin = "0% 50%"; // Rotate around one edge instead of the middle
line.style.transform = "rotate(" + (angle) + "deg)";

// Add the line to the SECOND image's parent element.
// It's the 2nd image instead of 1st because of the order we did the math in calculating the angle
document.getElementById("two").appendChild(line);
body, img {
  margin: 0;
  padding: 0;
  display: block;
}

#container {
  position: relative;
  background: #ddd;
  width: 320px;
  height: 240px;
}

.img-container {
  position: absolute;
}
<div id="container">
  <div id="one" class="img-container" style="left: 50px; top: 100px;" >
    <img src="http://imgur.com/8B1rYNY.png" />
  </div>
  <div id="two" class="img-container" style="left: 150px; top: 190px;" >
    <img src="http://imgur.com/8w6LAV6.png" />
  </div>
</div>

如果您希望线条出现在图像后面而不是前面,您可以修改它们的 z-index 值以便它们正确排序。

编辑:如果图像大小完全相同,则以上方法有效。如果它们大小不同,请计算图像的中心点并使用它而不是 getBoundingClientRect().

的左上角
// Get the position of the first image
var imgOneRect = document.getElementById("one").getBoundingClientRect();
var imgOnePosition = {
    left: (imgOneRect.left + imgOneRect.right) / 2,
    top: (imgOneRect.top + imgOneRect.bottom) / 2
}

// Get the position of the second image
var imgTwoRect = document.getElementById("two").getBoundingClientRect();
var imgTwoPosition = {
    left: (imgTwoRect.left + imgTwoRect.right) / 2,
    top: (imgTwoRect.top + imgTwoRect.bottom) / 2
}