three.js

Specify three.js graph size


How can I assign a width to the graph shown here - e.g. as a nested, padded element? As shown, the graph takes up the entire page width; I'd like to specify a size, e.g. 800px x 600px.

Is a CSS solution possible, e.g. containing <div id="3d-graph"></div> within another DIV element?

Code source: https://github.com/vasturiano/3d-force-graph ("Images as nodes")

<head>
  <script src="//unpkg.com/3d-force-graph"></script>
</head>

<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.  Nam ut fringilla enim. </p>

<div id="3d-graph"></div>

<p>Suspendisse efficitur pulvinar elementum. Vestibulum a est eu erat rutrum scelerisque non et diam.</p>

<script type="module">
  import SpriteText from "https://esm.sh/three-spritetext";

  const Graph = new ForceGraph3D(document.getElementById('3d-graph'))
    .jsonUrl('https://raw.githubusercontent.com/vasturiano/3d-force-graph/c8019651c7a851ebcd7ef595123b631fe6eca3eb/example/datasets/miserables.json')
    .nodeAutoColorBy('group')
    .nodeThreeObject(node => {
        const sprite = new SpriteText(node.id);
        sprite.material.depthWrite = false;
        sprite.color = node.color;
        sprite.textHeight = 6;
        return sprite;
      });
</script>
</body>


Solution

  • Through the Graph.width(x) and Graph.height(x) methods you change the size of the Canvas, not the graph itself. What you expect, i.e. manipulation of the graph itself, cannot be done through CSS. CSS defines the width and height on the x and y axis, moreover, it does not manipulate what is in the Canvas, but the Canvas itself as a DOM element. To scale the graph itself, you also need the z axis, because we move in three dimensions. Manipulating the graph itself through the scale method is not possible. Mainly, probably the best/easiest solution is to scale the scene. Attempting to manipulate the graph itself involves manipulating nodes and links.

    Try call method scene:

    const scene = Graph.scene();
    scene.scale.set(1.5, 1.5, 1.5);
    

    You can call the width, height and scene methods together and thus adapt the graph to the Canvas, and the Canvas itself. This is especially helpful when you expect other objects on the scene, in addition to the graph.

    WARNING: Multiple instances of Three.js being imported. error

    Warning occurs when you jave multiple versions or instances of the Three.js loaded in your project. If you use 3d-force-graph or three-spritetext, it may also bring in its own versions of Three. Make sure that you only loading one version of Three.js and that all other libraries are using the same instance.

    BTW

    In other hand you can create your own graph.

    https://codepen.io/Lucas_Mas/pen/bGXyQVO