思路:在一个定位元素中找到两个点的坐标,新创建一个div,然后使用数学运算,算出长度,角度deg,把长度给这个div,使用css反转deg角度,通过两个点左边计算div中心点坐标,由此可得div坐标
drawLine = (startObj, endObj, index) => {
// 起点元素中心坐标
const startY = startObj.y;
const startX = startObj.x;
// 终点元素中心坐标
const endY = endObj.y;
const endX = endObj.x;
// 用勾股定律计算出斜边长度及其夹角(即连线的旋转角度)
const lx = endX - startX;
const ly = endY - startY;
// 计算连线长度
const length = Math.sqrt(lx * lx + ly * ly);
// 弧度值转换为角度值
const c = 360 * Math.atan2(ly, lx) / (2 * Math.PI);
// 连线中心坐标
const midX = (endX + startX) / 2;
const midY = (endY + startY) / 2
const deg = c <= -90 ? (360 + c) : c; // 负角转换为正角
return (
<div
className="line"
style={{
top: midY, left: midX - length / 2, length, transform: `rotate(${deg}deg)`, borderColor: colorList[index],
}}
/>
)
}