G6(二)G6图适配画布大小

556 阅读2分钟

背景

G6渲染的图形数据,有些元素显示在画布区域之外。即实际的图被画布截断了,窗口可视区域只能看见部分内容。

G6渲染远程数据

要渲染的远程数据地址:gw.alipayobjects.com/os/basement…

实现代码:

import G6 from "@antv/g6";
import { useRef, useEffect } from "react";

const Toturial = () => {
    const containerRef = useRef(null);
    const graphRef = useRef();
    useEffect(() => {
        if (graphRef.current || !containerRef.current) return;
        const graph = new G6.Graph({
            container: containerRef.current, // String | HTMLElement,必须,在 Step 1 中创建的容器 id 或容器本身
            width: 800, // Number,必须,图的宽度
            height: 600, // Number,必须,图的高度
        });

        onLoadData((data) => {
            graph.data(data); // 绑定数据
            graph.render(); // 渲染图
            graphRef.current = graph;
        });
    }, []);

    const onLoadData = async (callback) => {
        const response = await fetch(
            "https://gw.alipayobjects.com/os/basement_prod/6cae02ab-4c29-44b2-b1fd-4005688febcb.json"
        );
        const remoteData = await response.json();
        callback(remoteData);
    };

    return (
        <div
            ref={containerRef}
            style={{ border: "2px solid #000", display: "inline-block" }}
        ></div>
    );
};

export default Toturial;

效果:

image.png

乍看之下,图像有点奇怪,实际上数据已经正确的加载了进来。由于数据量比较大,节点和边都非常的多,显得内容比较杂乱。另外由于画布大小的限制,实际的图被画布截断了,目前只能看见部分内容。

数据中发现节点定义了位置信息 x 与 y,并且很多节点的 x 和 y 不在图的宽高(width: 800, height: 600)范围内:

{
  "nodes": [
    { "id": "0", "label": "n0", "class": "c0", "x": 1000, "y": -100 },
    { "id": "1", "label": "n1", "class": "c0", "x": 300, "y": -10 }
    //...
  ],
  "edges": [
    //...
  ]
}

由于 G6 在读取数据时,发现了数据中带有位置信息(x 和 y),就会按照该位置信息进行绘。

优化不完整显示

为优化超出屏幕到问题,G6 提供了图的两个相关配置项:

  • fitView:设置是否将图适配到画布中;
  • fitViewPadding:画布上四周的留白宽度。

将实例化图的代码更改为如下形式:

const graph = new G6.Graph({
    container: containerRef.current, // String | HTMLElement,必须,在 Step 1 中创建的容器 id 或容器本身
    width: 800, // Number,必须,图的宽度
    height: 600, // Number,必须,图的高度
    fitView: true, // 是否将图适配到画布中
    fitViewPadding: [20, 40, 50, 20], // 画布上四周的留白宽度
});

将会生成如下图:

image.png

可以看到,图像已经可以自动适配画布的大小,完整的显示了出来。