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

求可在HTML元素间绘制带锁连线的CSS/JavaScript库

实现元素间带锁样式连线的工具推荐

需求说明:需要在文本框(或其他任意元素)之间绘制连线,优先支持带锁样式的连线,目标效果参考下图:
示例效果1
示例效果2

  • JointJS
    这是专门面向交互式图表、元素连线场景的库,对元素关联、自定义连线样式支持非常友好。你可以直接创建可拖拽的元素(文本框等),然后通过配置连线的markers或者自定义连线模板,在连线中间插入锁样式的图标(可以用内置SVG图形或自定义SVG锁),完全满足需求。核心代码思路如下:

    // 初始化画布
    const graph = new joint.dia.Graph();
    const paper = new joint.dia.Paper({
      el: document.getElementById('container'),
      model: graph,
      width: 800,
      height: 600
    });
    // 创建文本框元素
    const input1 = new joint.shapes.basic.Rect({
      position: { x: 100, y: 100 },
      size: { width: 120, height: 40 },
      attrs: { rect: { fill: 'white', stroke: 'black' }, text: { text: '输入框1' } }
    });
    const input2 = new joint.shapes.basic.Rect({
      position: { x: 400, y: 100 },
      size: { width: 120, height: 40 },
      attrs: { rect: { fill: 'white', stroke: 'black' }, text: { text: '输入框2' } }
    });
    graph.addCells([input1, input2]);
    // 创建带锁样式的连线
    const link = new joint.dia.Link({
      source: { id: input1.id },
      target: { id: input2.id },
      attrs: {
        line: { stroke: '#ff0000', strokeWidth: 2 },
        // 自定义中间锁标记(SVG路径可替换为你需要的锁样式)
        markerMid: {
          d: 'M12 17c0 1.657-1.343 3-3 3s-3-1.343-3-3V9c0-1.657 1.343-3 3-3s3 1.343 3 3v8zm-1-11c0-.552-.448-1-1-1s-1 .448-1 1v1H9v-1c0-1.103.897-2 2-2s2 .897 2 2v1h-1v-1z',
          fill: '#ff0000',
          width: 20,
          height: 20
        }
      }
    });
    graph.addCell(link);
    
  • SVG.js
    轻量的SVG操作库,灵活度极高,适合自定义绘制图形。实现步骤:

    1. 创建SVG容器覆盖在页面元素上方
    2. 获取两个目标元素的位置、尺寸,计算连线的起点(比如元素右侧中心)和终点(元素左侧中心)
    3. 绘制直线或贝塞尔曲线连线
    4. 在连线中点位置绘制锁的SVG图形(或插入自定义锁图标)
      适合不需要复杂交互、追求自定义样式的场景。
  • 原生JS + SVG/CSS(无库方案)
    若不想引入第三方库,可直接用原生实现:

    1. 动态创建<svg>元素作为画布,设置position: absolute覆盖在页面上
    2. 通过getBoundingClientRect()获取元素坐标,计算连线的起点和终点
    3. 创建<line>元素绘制连线,再创建<path>或引入锁图标(如Font Awesome的锁图标)定位在连线中点
    4. 监听窗口resize或元素位置变化,重新计算并更新连线坐标
      该方案体积最小,适合轻量需求场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:18:33