swimlane / ngx-graph

Graph visualization library for angular
https://swimlane.github.io/ngx-graph
MIT License
933 stars 285 forks source link

Cannot set the graph with D3 Force Directed layout at center of the graph area #360

Open hieutranagi47 opened 3 years ago

hieutranagi47 commented 3 years ago

Describe the bug Set the graph at the center but the graph transforms to top-left of the view area.

To Reproduce Steps to reproduce the behavior: From the demo, change the layout type to "D3 Force Directed", then click the Center button

Expected behavior The graph will transform to the center of the view area.

Screenshots Screenshot

Demo Demo: https://stackblitz.com/edit/ngx-graph-demo-ukj2zc?file=src%2Fapp%2Fapp.component.ts

ngx-graph version Version: 7.1.2

hieutranagi47 commented 3 years ago

I fixed the issue by below changes:

  panTo(x: number, y: number): void {
    if (x === null || x === undefined || isNaN(x) || y === null || y === undefined || isNaN(y)) {
      return;
    }

    /**
      const panX = -this.panOffsetX - x * this.zoomLevel + this.dims.width / 2;
      const panY = -this.panOffsetY - y * this.zoomLevel + this.dims.height / 2;
    */
    let panX = 0;
    let panY = 0;
    if (this.layout instanceof D3ForceDirectedLayout) {
      panX = -this.panOffsetX + this.dims.width / 2;
      panY = -this.panOffsetY + this.dims.height / 2;
    } else {
      panX = -this.panOffsetX - x * this.zoomLevel + this.dims.width / 2;
      panY = -this.panOffsetY - y * this.zoomLevel + this.dims.height / 2;
    }

    this.transformationMatrix = transform(
      this.transformationMatrix,
      translate(panX / this.zoomLevel, panY / this.zoomLevel)
    );

    this.updateTransform();
  }

I don't know why, but it helped me. I'll try to find a root cause to fix it and create a PR later.

kempoo commented 3 years ago

are there any updates on this?

amykglen commented 1 year ago

is there any plan to fix this? it's kind of a show-stopper for me. it still seems to be an issue in version 8.0.2.

hieutranagi47 commented 1 year ago

@amykglen I am not sure about my fix, but it works. So you can fork the repo and replace the code of the panTo function with my above code to use first!