js 实现连线
实现 JavaScript 连线功能
连线功能通常用于图表、流程图或交互式 UI 中,以下是几种常见的实现方式:
使用 Canvas API
Canvas 提供了绘制线条的直接方法,适合动态或复杂的连线场景:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
function drawLine(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.strokeStyle = '#000';
ctx.lineWidth = 2;
ctx.stroke();
}
使用 SVG
SVG 是矢量图形标准,适合需要 DOM 交互的场景:

const svg = document.querySelector('svg');
function createLine(x1, y1, x2, y2) {
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', x1);
line.setAttribute('y1', y1);
line.setAttribute('x2', x2);
line.setAttribute('y2', y2);
line.setAttribute('stroke', 'black');
svg.appendChild(line);
}
使用 CSS + DOM
简单连线可以通过绝对定位的 div 和旋转实现:
function createDivLine(x1, y1, x2, y2) {
const line = document.createElement('div');
line.style.position = 'absolute';
line.style.backgroundColor = '#000';
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;
line.style.width = `${length}px`;
line.style.height = '2px';
line.style.left = `${x1}px`;
line.style.top = `${y1}px`;
line.style.transformOrigin = '0 0';
line.style.transform = `rotate(${angle}deg)`;
document.body.appendChild(line);
}
使用第三方库
对于复杂场景,可以考虑专用图形库:

贝塞尔曲线实现
需要曲线连线时可以使用二次或三次贝塞尔曲线:
// Canvas 中的二次贝塞尔曲线
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.quadraticCurveTo(100, 100, 150, 50);
ctx.stroke();
动态连线示例
结合鼠标事件实现交互式连线:
let isDrawing = false;
let startX, startY;
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
[startX, startY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mousemove', (e) => {
if (!isDrawing) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawLine(startX, startY, e.offsetX, e.offsetY);
});
canvas.addEventListener('mouseup', () => {
isDrawing = false;
});
以上方法可根据具体需求选择,Canvas 适合高性能绘制,SVG 适合需要 DOM 操作的场景,CSS 方案适合简单需求,第三方库能快速实现复杂功能。






