Alt

本文由ScriptEcho平台提供技术支持

项目地址:传送门

## 基于G6实现鱼眼透镜效果的可视化卡片

应用场景介绍

鱼眼透镜是一种交互技术,它允许用户放大和探索特定区域,同时保持周围环境的背景。在可视化场景中,鱼眼透镜效果可以帮助用户专注于特定数据点或区域,同时保持对整体数据的感知。

代码基本功能介绍

本代码使用G6库实现了鱼眼透镜效果,用户可以通过点击节点来启用鱼眼透镜,也可以通过按钮切换鱼眼透镜的开启和关闭。

功能实现步骤及关键代码分析说明

1. 初始化鱼眼透镜插件

let fisheye = new G6.Fisheye({
  r: 200,
  showLabel: true,
  delegateStyle: {
    fill: '#f00',
    lineDash: [5, 5],
    stroke: '#666',
  },
});
  • r: 鱼眼透镜的半径。
  • showLabel: 是否显示节点标签。
  • delegateStyle: 鱼眼透镜区域内节点的样式。

2. 添加按钮控制鱼眼透镜

// clear the fisheye effect button
const clearButton = document.createElement('input');
clearButton.type = 'button';
clearButton.value = 'Clear';
clearButton.style.height = '25px';
clearButton.style.width = '100px';
buttonContainer.appendChild(clearButton);

// enable/disable the fisheye lens button
const switchButton = document.createElement('input');
switchButton.type = 'button';
switchButton.value = 'Disable';
switchButton.style.height = '25px';
switchButton.style.width = '100px';
switchButton.style.marginLeft = '10px';
buttonContainer.appendChild(switchButton);
  • clearButton: 点击清除鱼眼透镜效果。
  • switchButton: 点击切换鱼眼透镜的开启和关闭。

3. 监听按钮事件

clearButton.addEventListener('click', (e) => {
  fisheye.clear();
});
switchButton.addEventListener('click', (e) => {
  if (switchButton.value === 'Disable') {
    switchButton.value = 'Enable';
    graph.removePlugin(fisheye);
  } else {
    switchButton.value = 'Disable';
    fisheye = new G6.Fisheye({
      r: 200,
      showLabel: true,
    });
    graph.addPlugin(fisheye);
  }
});
  • 监听clearButton的点击事件,清除鱼眼透镜效果。
  • 监听switchButton的点击事件,切换鱼眼透镜的开启和关闭。

4. 加载数据并渲染图表

fetch('https://gw.alipayobjects.com/os/bmw-prod/afe8b2a6-f691-4070-aa73-46fc07fd1171.json')
  .then((res) => res.json())
  .then((data) => {
    data.nodes.forEach((node) => {
      node.label = node.id;
      node.size = Math.random() * 30 + 10;
      node.style = {
        fill: colors[Math.floor(Math.random() * 9)],
        lineWidth: 0,
      };
    });
    graph.data(data);
    graph.render();
    graph.getNodes().forEach((node) => {
      node
        .getContainer()
        .getChildren()
        .forEach((shape) => {
          if (shape.get('type') === 'text') shape.hide();
        });
    });
  });
  • 从指定URL加载JSON数据。
  • 对数据进行处理,设置节点的标签、大小和样式。
  • 将数据加载到图表中并渲染。
  • 隐藏节点的文本标签。

5. 响应窗口大小变化

if (typeof window !== 'undefined')
  window.onresize = () => {
    if (!graph || graph.get('destroyed')) return;
    if (!container || !container.scrollWidth || !container.scrollHeight) return;
    graph.changeSize(container.scrollWidth, container.scrollHeight);
  };
  • 监听窗口大小变化事件。
  • 如果图表存在且未被销毁,则调整图表大小以适应窗口大小变化。

总结与展望

开发这段代码过程中的经验与收获:

  • 了解了G6库中鱼眼透镜插件的使用。
  • 掌握了如何使用按钮控制鱼眼透镜效果。
  • 理解了如何加载数据并渲染图表。

未来该卡片功能的拓展与优化:

  • 支持自定义鱼眼透镜的半径和样式。
  • 集成其他交互功能,如缩放和拖动。
  • 优化鱼眼透镜效果的性能。

    更多组件:

    获取更多Echos

    本文由ScriptEcho平台提供技术支持

    项目地址:传送门

    扫码加入AI生成前端微信讨论群:
    扫码加入群聊


ScriptEcho
9 声望0 粉丝

轻松上手的AI前端代码生成工具,实现原型图/设计图/草图一键生成页面代码