---
title: "聚焦元素 FocusElement"
description: "聚焦元素 FocusElement"
language: "zh"
canonical: "https://g6.antv.antgroup.com/zh/manual/behavior/FocusElement/"
version: "5.1.1"
---

## 概述

FocusElement 是 G6 中用于实现元素聚焦功能的内置交互，支持通过点击元素将其聚焦到视图中心。这个交互可以帮助用户快速定位和关注特定的图元素。

## 使用场景

- 快速将关注的节点或边居中显示

## 在线体验



```ts
import { createGraph } from '/demo-runtime.ts';

createGraph(
  {
    data: {
      nodes: [
        { id: 'node-1', style: { x: 200, y: 100 } },
        { id: 'node-2', style: { x: 360, y: 100 } },
        { id: 'node-3', style: { x: 280, y: 220 } },
      ],
      edges: [
        { source: 'node-1', target: 'node-2' },
        { source: 'node-1', target: 'node-3' },
        { source: 'node-2', target: 'node-3' },
      ],
    },
    node: { style: { fill: '#7e3feb' } },
    edge: { style: { stroke: '#8b9baf' } },
    behaviors: [
      {
        type: 'focus-element',
        key: 'focus-element',
      },
    ],
    plugins: [{ type: 'grid-line', size: 30 }],
    animation: true,
  },
  { width: 600, height: 300 },
  (gui, graph) => {
    const options = {
      key: 'focus-element',
      type: 'focus-element',
      animation: true,
      enable: true,
    };
    const optionFolder = gui.addFolder('FocusElement Options');
    optionFolder.add(options, 'type').disable(true);
    optionFolder.add(options, 'animation');
    optionFolder.add(options, 'enable');

    optionFolder.onChange(({ property, value }) => {
      graph.updateBehavior({
        key: 'focus-element',
        [property]: value,
      });
      graph.render();
    });
  },
);
```



## 基本用法

在图配置中添加这一交互：

**1. 快速配置（静态）**

使用字符串形式直接声明：

```javascript
const graph = new Graph({
  // 其他配置...
  behaviors: ['focus-element'],
});
```

**2. 对象配置（推荐）**

使用对象形式进行配置，支持自定义参数：

```javascript
const graph = new Graph({
  // 其他配置...
  behaviors: [
    {
      type: 'focus-element',
      animation: {
        duration: 500,
        easing: 'ease-in',
      },
    },
  ],
});
```

## 配置项

| 配置项    | 说明                                                                                                                                                                                                                                                           | 类型                                                            | 默认值                                 | 必选 |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | -------------------------------------- | ---- |
| type      | 交互类型名称                                                                                                                                                                                                                                                   | string                                                          | `focus-element`                        | ✓    |
| animation | 聚焦动画效果设置                                                                                                                                                                                                                                               | [ViewportAnimationEffectTiming](#viewportanimationeffecttiming) | `{ duration: 500, easing: 'ease-in' }` |      |
| enable    | 是否启用聚焦功能                                                                                                                                                                                                                                               | boolean \| ((event: IElementEvent) => boolean)                  | true                                   |      |
| trigger   | 同时按下快捷键才能聚焦元素 **按键参考：** _<a href="https://developer.mozilla.org/zh-CN/docs/Web/API/UI_Events/Keyboard_event_key_values" target="_blank" rel="noopener noreferrer">MDN Key Values</a>_ 。若设为**空数组**时则表示不需要按下其他按键配合 <br/> | string[] \| (`Control` \| `Shift`\| `Alt` \| `......`)[]        | []                                     |      |

### ViewportAnimationEffectTiming

```typescript
type ViewportAnimationEffectTiming =
  | boolean // true 启用默认动画，false 禁用动画
  | {
      easing?: string; // 动画缓动函数：'ease-in-out'、'ease-in'、'ease-out'、'linear'
      duration?: number; // 动画持续时间(毫秒)
    };
```

## 代码示例

### 基础聚焦功能

```javascript
const graph = new Graph({
  container: 'container',
  width: 800,
  height: 600,
  behaviors: ['focus-element'],
});
```

### 自定义动画效果

```javascript
const graph = new Graph({
  // 其他配置...
  behaviors: [
    {
      type: 'focus-element',
      animation: {
        duration: 800,
        easing: 'ease-in-out',
      },
    },
  ],
});
```

### 条件性启用聚焦

```javascript
const graph = new Graph({
  // 其他配置...
  behaviors: [
    {
      type: 'focus-element',
      enable: (event) => {
        // 只对节点启用聚焦，边不聚焦
        return event.target.type === 'node';
      },
    },
  ],
});
```

## 实际案例



```ts

import { Graph } from '@antv/g6';

const data = {
  nodes: [
    { id: 'node1', combo: 'combo1', style: { x: 110, y: 150 } },
    { id: 'node2', combo: 'combo1', style: { x: 190, y: 150 } },
    { id: 'node3', combo: 'combo2', style: { x: 150, y: 260 } },
  ],
  edges: [{ source: 'node1', target: 'node2' }],
  combos: [{ id: 'combo1', combo: 'combo2' }, { id: 'combo2' }],
};

const graph = new Graph({
  container: 'container',
  node: {
    style: { labelText: (d) => d.id },
  },
  data,
  behaviors: ['collapse-expand', 'focus-element'],
});

graph.render();
```
### demo-runtime.ts

```ts
import { Graph } from '@antv/g6';
import GUI from 'lil-gui';

export function addPanel(renderPanel: (gui: GUI) => void) {
  const gui = new GUI({ container: document.body });
  gui.title('Control');
  Object.assign(gui.domElement.style, { position: 'absolute', top: '0', right: '0', zIndex: '10' });
  renderPanel(gui);
  addEventListener('pagehide', () => gui.destroy(), { once: true });
}

export async function createGraph(
  options: ConstructorParameters<typeof Graph>[0],
  size: { width?: number; height?: number } = {},
  renderPanel?: (gui: GUI, graph: Graph) => void,
) {
  const container = document.createElement('div');
  Object.assign(container.style, {
    width: '100%',
    maxWidth: `${size.width || 600}px`,
    height: `${size.height || 400}px`,
  });
  document.getElementById('container')!.append(container);
  const graph = new Graph({ ...size, ...options, width: container.clientWidth, container, autoResize: true });
  addEventListener('pagehide', () => graph.destroy(), { once: true });
  await graph.render();
  if (renderPanel) addPanel((gui) => renderPanel(gui, graph));
  return container;
}
```
