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

如何在鼠标点击的X、Y坐标位置创建HTML元素以实现点连线功能?

实现点击创建点并连线的方案

核心实现思路

  • 创建点元素时,使用position: absolute进行定位,通过鼠标事件的clientX和clientY值设置元素的left与top属性
  • 维护一个数组记录已创建的点,当数组内有两个点时,生成连线元素并重置数组,准备下一组点的创建

完整代码示例

HTML结构

<!-- 承载点和连线的容器,设置相对定位作为绝对定位元素的参考 -->
<div id="canvas" style="position: relative; width: 100vw; height: 100vh; background: #f5f5f5;"></div>

TypeScript实现代码

// 存储点击生成的点元素
const points: HTMLElement[] = [];
const canvas = document.getElementById('canvas') as HTMLElement;

const mousePos = (e: PointerEvent) => {
  const _Xpos = e.clientX;
  const _Ypos = e.clientY;

  // 创建点元素
  const point = document.createElement('div');
  point.style.position = 'absolute';
  point.style.width = '8px';
  point.style.height = '8px';
  point.style.borderRadius = '50%';
  point.style.backgroundColor = '#2196F3';
  // 让点的中心对准点击位置,若需要左上角对齐可删除此行
  point.style.left = `${_Xpos}px`;
  point.style.top = `${_Ypos}px`;
  point.style.transform = 'translate(-50%, -50%)';
  canvas.appendChild(point);

  points.push(point);

  // 当存在两个点时,创建连线
  if (points.length === 2) {
    createLine(points[0], points[1]);
    // 清空数组,准备下一组点
    points.length = 0;
  }
};

// 生成两点间连线的函数
function createLine(point1: HTMLElement, point2: HTMLElement) {
  // 获取两个点的位置信息
  const rect1 = point1.getBoundingClientRect();
  const rect2 = point2.getBoundingClientRect();
  
  // 计算两点的中心坐标
  const x1 = rect1.left + rect1.width / 2;
  const y1 = rect1.top + rect1.height / 2;
  const x2 = rect2.left + rect2.width / 2;
  const y2 = rect2.top + rect2.height / 2;

  // 计算连线的长度和旋转角度
  const length = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
  const angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;

  // 创建连线元素
  const line = document.createElement('div');
  line.style.position = 'absolute';
  line.style.width = `${length}px`;
  line.style.height = '2px';
  line.style.backgroundColor = '#333';
  line.style.left = `${x1}px`;
  line.style.top = `${y1}px`;
  line.style.transformOrigin = '0 50%';
  line.style.transform = `rotate(${angle}deg)`;
  
  canvas.appendChild(line);
}

window.addEventListener("click", mousePos);

关键细节说明

  • 容器#canvas设置为relative定位,确保内部绝对定位的点和连线以它为坐标参考系
  • 点元素的transform: translate(-50%, -50%)是为了让点的中心精准对齐点击位置,若不需要此效果可直接删除该行
  • 连线通过计算两点的距离和角度,利用CSS旋转和长度设置实现两点间的直线连接

内容的提问来源于stack exchange,提问作者Mustafa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:55:18