vasturiano / d3-force-3d

Force-directed graph layout in 1D, 2D or 3D using velocity Verlet integration.
https://observablehq.com/@vasturiano/multi-dimensional-d3-force-simulation
MIT License
373 stars 54 forks source link

Can I use this without 3d-force-graph #3

Closed leixu2txtek closed 4 years ago

leixu2txtek commented 6 years ago

This repository is great for me, and Can I use this without 3d-force-graph. Thx.

image

Can I drag & move like 3d-force-graph

from a newcomer of d3 :)

leixu2txtek commented 6 years ago

    import { select, scaleOrdinal, schemeCategory10, zoom, event } from 'd3';
    import * as d3 from 'd3-force-3d';

    this.nodes = [];
    this.edges = [];

    const canvas = this.$el;
    const width = canvas.width;
    const height = canvas.height;
    const context = canvas.getContext('2d');

    const color = scaleOrdinal(schemeCategory10);

    select(canvas).call(zoom().scaleExtent([1 / 4, 5]).on('zoom', () => {...}));

     const simulation = d3.forceSimulation()
      .force('link', d3.forceLink().id(function (d) {

        return d.id;

      }).distance(150))
      .numDimensions(3)
      .force('charge', d3.forceManyBody().strength(-200))
      .force('center', d3.forceCenter(width / 2, height / 2));

    simulation.nodes(this.nodes).on('tick', () => {

      context.clearRect(0, 0, width, height);
      context.beginPath();

      this.edges.forEach(function (d) {

        context.moveTo(d.source.x, d.source.y);
        context.lineTo(d.target.x, d.target.y);
      });

      context.strokeStyle = '#ccc';
      context.stroke();

      this.nodes.forEach(function (d) {

        context.beginPath();
        context.fillStyle = color(d.group);

        context.moveTo(d.x, d.y);
        context.arc(d.x, d.y, d.size, 0, 2 * Math.PI);

        context.closePath();
        context.fill();
      });

    });

    simulation.force('link').links(this.edges);
vasturiano commented 6 years ago

Hi @leixu2txtek, you can certainly use d3-force-3d outside of 3d-force-graph. It seems you are actually already doing so. :)

As you probably know, any type of DOM manipulation and interaction will be up to your consuming application. If you need an example on how to do drag nodes in canvas for example, you could look into how it's implemented in force-graph as it supports this functionality. This would give you a good starting point: https://github.com/vasturiano/force-graph/blob/master/src/force-graph.js#L226

I'm sure you can also find other examples online on how to do this. Good luck!