繁体   English   中英

用 CSS 和 JS 在两点之间画一条对角线

[英]Draw a diagonal line between two points with CSS and JS

我试图用 CSS 和 JS 在这样的元素之间画一条对角线。

在此处输入图像描述

我有两个 div,我知道它们的左坐标和上坐标。

<div class='wrapper'>
  <div class='point' style='left: 40px; top: 40px;'></div>
  <div class='point' style='left: 260px; top: 120px;'></div>
  <div class='line'></div>
</div>

但是这里如何计算旋转度数和高度值呢?

const point1 = document.getElementsByClassName('point')[0]
const point2 = document.getElementsByClassName('point')[1]
const line = document.getElementsByClassName('line')[0]

const lineLeft = parseInt(point1.style.left) + point1.clientWidth
const lineTop = parseInt(point1.style.top) + point1.clientHeight

line.style.left = `${lineLeft}px`
line.style.top = `${lineTop}px`
line.style.height = '?'
line.style.transform = 'rotate(?deg)'

是它的 CodePen 版本。

如果您必须通过 CSS 和 Javascript 执行此操作,这是可能的,但并不理想。 您必须做一些额外的工作来计算点之间的角度和点之间的距离。 看看下面的示例:

 const point1 = document.getElementsByClassName('point')[0] const point2 = document.getElementsByClassName('point')[1] const line = document.getElementsByClassName('line')[0] // Find the points based off the elements left and top var p1 = {x: point1.offsetLeft, y: point1.offsetTop}; var p2 = {x: point2.offsetLeft, y: point2.offsetTop}; // Get distance between the points for length of line var a = p1.x - p2.x; var b = p1.y - p2.y; var length = Math.sqrt( a*a + b*b ); // Get angle between points var angleDeg = Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI; // Get distance from edge of point to center var pointWidth = point1.clientWidth / 2; var pointHeight = point1.clientWidth / 2; // Set line distance and position // Add width/height from above so the line starts in the middle instead of the top-left corner line.style.width = length + 'px'; line.style.left = (p1.x + pointWidth)+ 'px'; line.style.top = (p1.y + pointHeight) + 'px'; // Rotate line to match angle between points line.style.transform = "rotate(" + angleDeg + "deg)";
 .wrapper { width: 320px; height: 180px; position: relative; border: 1px solid #aaa; background-color: #eee; }.point { width: 20px; height: 20px; position: absolute; background-color: #555; }.line { position: absolute; height:2px; background-color: #d63030; transform-origin: left; }
 <div class='wrapper'> <div class='point' style='left: 40px; top: 40px;'></div> <div class='point' style='left: 260px; top: 120px;'></div> <div class='line'</div> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM