我的页面中有很多图像,我正在寻找一种方法来绘制一条线,将一个图像连接到另一个图像(它不必是箭头,只是一条法线。)例如。 ,让我们将($)视为图像:
$
$
现在我如何用线条连接这两个图像($)?
谢谢!
答案 0 :(得分:4)
由于您似乎在询问基本的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>
&#13;
如果您希望该线条显示在图片后面而不是前面,您可以修改其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
}
答案 1 :(得分:0)