---
title: "随机摇摆线"
language: "zh"
canonical: "https://x6.antv.antgroup.com/zh/examples/edge/connector/wobble/"
version: "3.x"
---

# 随机摇摆线

[运行示例](https://x6.antv.antgroup.com/zh/examples/edge/connector/wobble/)

[资料索引](/llms.txt)

页面需要一个 `id="container"` 的 DOM 元素。以下为原始示例源码。

## 源码

```ts
import { Graph, Path, Point } from '@antv/x6'

// 帮助文档：https://x6.antv.vision/zh/docs/api/registry/connector#registry
Graph.registerConnector(
  'wobble',
  (sourcePoint, targetPoint, vertices, args) => {
    const spread = args.spread || 20
    const points = [...vertices, targetPoint].map((p) => Point.create(p))
    let prev = Point.create(sourcePoint)
    const path = new Path()
    path.appendSegment(Path.createSegment('M', prev))

    for (let i = 0, n = points.length; i < n; i += 1) {
      const next = points[i]
      const distance = prev.distance(next)
      let d = spread

      while (d < distance) {
        const current = prev.clone().move(next, -d)
        current.translate(
          Math.floor(7 * Math.random()) - 3,
          Math.floor(7 * Math.random()) - 3,
        )
        path.appendSegment(Path.createSegment('L', current))
        d += spread
      }

      path.appendSegment(Path.createSegment('L', next))
      prev = next
    }

    return path
  },
  true,
)

const graph = new Graph({
  container: document.getElementById('container'),
  grid: true,
})

const source = graph.addNode({
  x: 120,
  y: 40,
  width: 100,
  height: 40,
  attrs: {
    body: {
      fill: '#f5f5f5',
      stroke: '#d9d9d9',
    },
  },
})

const target = graph.addNode({
  x: 400,
  y: 260,
  width: 100,
  height: 40,
  attrs: {
    body: {
      fill: '#f5f5f5',
      stroke: '#d9d9d9',
    },
  },
})

graph.addEdge({
  source,
  target,
  vertices: [
    { x: 200, y: 200 },
    { x: 380, y: 120 },
  ],
  connector: {
    name: 'wobble',
    args: {
      spread: 10,
    },
  },
  attrs: {
    line: {
      stroke: '#722ed1',
    },
  },
})
```
