You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过JavaScript在HTML div元素间绘制SVG连线不生效问题咨询

问题原因

  • SVG未设置尺寸与定位,默认没有铺满父容器.graph,内部坐标体系和容器不匹配
  • getBoundingClientRect()返回的是相对于浏览器视口的绝对坐标,而SVG line的属性是相对于SVG自身左上角的坐标,两者基准不一致
  • 当前读取的是圆形div左上角的坐标,连线会接在圆的角落而不是中心,视觉效果不符合预期

修改方案

  1. 新增CSS样式,让SVG铺满整个父容器:
/* 加入到原有CSS文件中即可 */
.graph svg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
  1. 调整JS逻辑,修正坐标计算规则:
const circle1 = document.querySelector('.circle--1');
const circle2 = document.querySelector('.circle--2');
const line1 = document.querySelector('#line-1');
const svg = document.querySelector('.graph svg');

// 获取各元素边界信息
const svgRect = svg.getBoundingClientRect();
const c1Rect = circle1.getBoundingClientRect();
const c2Rect = circle2.getBoundingClientRect();

// 计算两个圆心相对于SVG的坐标
const x1 = c1Rect.left + c1Rect.width / 2 - svgRect.left;
const y1 = c1Rect.top + c1Rect.height / 2 - svgRect.top;
const x2 = c2Rect.left + c2Rect.width / 2 - svgRect.left;
const y2 = c2Rect.top + c2Rect.height / 2 - svgRect.top;

// 给line属性赋值
line1.setAttribute('x1', x1);
line1.setAttribute('y1', y1);
line1.setAttribute('x2', x2);
line1.setAttribute('y2', y2);

额外说明

原有CSS中重复定义了两次.circle--1的样式,前者会被后者覆盖,若不是刻意编写的冗余代码可以直接删除。

内容的提问来源于stack exchange,提问作者Manjesh R V

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 11:57:02