js 实现连线
使用 Canvas 实现连线
Canvas 提供了基础的绘图 API,可以通过 beginPath、moveTo 和 lineTo 方法绘制线段。以下是一个简单的示例:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 绘制一条从 (50, 50) 到 (200, 200) 的线段
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(200, 200);
ctx.strokeStyle = 'black';
ctx.stroke();
使用 SVG 实现连线
SVG 通过 <line> 元素直接支持线段绘制,属性包括起点 (x1, y1) 和终点 (x2, y2):
<svg width="300" height="300">
<line x1="50" y1="50" x2="200" y2="200" stroke="black" stroke-width="2"/>
</svg>
动态创建 SVG 连线可通过 JavaScript 操作 DOM:
const svg = document.querySelector('svg');
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', '50');
line.setAttribute('y1', '50');
line.setAttribute('x2', '200');
line.setAttribute('y2', '200');
line.setAttribute('stroke', 'black');
svg.appendChild(line);
使用库简化连线逻辑
jsPlumb
适用于流程图、拓扑图等场景,支持拖拽、连线样式定制:
import { jsPlumb } from 'jsplumb';
jsPlumb.ready(() => {
jsPlumb.connect({
source: 'element1',
target: 'element2',
anchors: ['Right', 'Left'],
connector: ['Straight']
});
});
LeaderLine
专为元素间连线设计,支持动画和样式调整:
import LeaderLine from 'leader-line';
const line = new LeaderLine(
document.getElementById('start'),
document.getElementById('end'),
{ color: 'blue', dash: { animation: true } }
);
动态响应式连线
监听元素位置变化并更新连线坐标:
function updateLine() {
const start = document.getElementById('start').getBoundingClientRect();
const end = document.getElementById('end').getBoundingClientRect();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(start.x + start.width/2, start.y + start.height/2);
ctx.lineTo(end.x + end.width/2, end.y + end.height/2);
ctx.stroke();
}
// 监听窗口变化或元素移动
window.addEventListener('resize', updateLine);
贝塞尔曲线连线
通过二次或三次贝塞尔曲线实现平滑连线:
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.quadraticCurveTo(150, 200, 250, 50); // 控制点 (150,200),终点 (250,50)
ctx.stroke();
数学公式描述(二次贝塞尔曲线):
$B(t) = (1-t)^2 P_0 + 2(1-t)t P_1 + t^2 P_2$
其中 $P_0$ 为起点,$P_1$ 为控制点,$P_2$ 为终点,$t \in [0,1]$。







