Exploring d3.js: Unleashing the Power of Force Layouts and

I have recently forked and made modifications to a JSfiddle, the link can be found here. Below is the js-code I am currently working with:

var graph = {
  "nodes": [{
    "name": "a",
    "group": 1
  }, {
    "name": "a",
    "group": 1
  }, {
    "name": "a",
    "group": 1
  }, {
    "name": "a",
    "group": 1
  }, {
    "name": "b",
    "group": 8
  }],
  "links": [{
    "source": 1,
    "target": 0,
    "value": 1
  }, {
    "source": 2,
    "target": 0,
    "value": 1
  }, {
    "source": 3,
    "target": 0,
    "value": 1
  }, {
    "source": 4,
    "target": 0,
    "value": 1
  }]
};
var width = 600,
  height = 600;

var color = d3.scale.category20();

var force = d3.layout.force()
  .charge(-120)
  .linkDistance(30)
  .size([width, height]);

var svg = d3.select("body").append("svg")
  .attr("width", width)
  .attr("height", height);

var drawGraph = function(graph) {
  force
    .nodes(graph.nodes)
    .links(graph.links)
    .start();

  var link = svg.selectAll(".link")
    .data(graph.links)
    .enter().append("line")
    .attr("class", "link")
    .style("stroke-width", function(d) {
      return Math.sqrt(d.value);
    });

  var gnodes = svg.selectAll('g.gnode')
    .data(graph.nodes)
    .enter()
    .append('g')
    .classed('gnode', true)
    .call(force.drag);

  var node = gnodes.append("circle")
    .attr("class", "node")
    .attr("r", 10)
    .style("fill", function(d) {
      return color(d.group);
    });

  node.append("title")
    .text(function(d) {
      return d.name;
    });

  var labels = gnodes.append("text")
    .text(function(d) {
      return d.name;
    })
    .attr('text-anchor', 'middle')
    .attr('font-size', 12.0)
    .attr('font-weight', 'bold')
    .attr('y', 2.5)
    .attr('fill', d3.rgb(50, 50, 50))
    .attr('class', 'node-label')
    .append("svg:title")
    .text(function(d) {
      return d.name;
    });

  force.on("tick", function() {
    link.attr("x1", function(d) {
        return d.source.x;
      })
      .attr("y1", function(d) {
        return d.source.y;
      })
      .attr("x2", function(d) {
        return d.target.x;
      })
      .attr("y2", function(d) {
        return d.target.y;
      })
      .each(function(d) {
        console.log(Math.sqrt((d.source.x - d.target.x) * (d.source.x - d.target.x) + (d.source.y - d.target.y) * (d.source.y - d.target.y)));
      });

    gnodes.attr("transform", function(d) {
      return 'translate(' + [d.x, d.y] + ')';
    });
  });
};

drawGraph(graph);

My current question revolves around the possibility of getting and extracting the node's positions after the Force-Directed Algorithm has finished rendering. My goal is to save these node positions in JSON format for use with a pre-rendered SVG graph in another framework. Ideally, I would like to have normalized position values based on a canvas size of 600*600.

Thank you in advance for any assistance provided!

Answer №1

To access the end event of force, which occurs after all calculations have been completed, you can retrieve nodes using var nodes = force.nodes() and then modify them according to your needs.

Check out this example to see nodes with their positions displayed in the console after all calculations are finished.

Keep in mind that this event will be triggered after each manipulation, so consider adding a flag to prevent it from being called every time if necessary.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Chartjs to Dynamically Update Data from Database Values

I'm encountering some difficulties while attempting to refresh my Chartjs doughnut chart with data retrieved from my database. Below is the ajax call that I've implemented successfully: $.ajax({ url: "<!--#include virtual="../include/e ...

Customizing the toString method within an object's definition

There was a question asked previously regarding the overriding of toString. Here is the answer provided: function Foo() {} Foo.prototype.toString = function() { return "this is Foo"; } However, my question is: Is it possible to include this prototy ...

Issue with unrecognized expression in JQuery when processing Ajax response

Recently, I implemented a JQuery Ajax Form on my website. $('#modal-body-sign-in').on('submit', '#sign-in', function(e) { e.preventDefault(); var data = $(this).serialize(); var url = $(this).attr(&apo ...

Can anyone help me with fixing the error message 'Cannot assign to read-only property 'exports' of the object' in React?

Recently, I decided to delve into the world of React and started building a simple app from scratch. However, I have run into an issue that is throwing the following error: Uncaught TypeError: Cannot assign to read-only property 'exports' of o ...

Guide on how to retrieve a list of objects from a controller and showcase them utilizing JQuery in a Spring MVC application with ajax functionality

Here is the controller code snippet: @Controller public class MainController { @Autowired SqlSession sqlSession; @Autowired Message messageVO; @RequestMapping(value="getMessages", method=RequestMethod.GET) public @ResponseBody List<Messag ...

Error message thrown by node express.js indicating that response headers cannot be reset once they have been sent

As a newcomer to both node and express, I may be making a silly mistake. If you want to see the complete source code, please visit: https://github.com/wa1gon/aclogGate/tree/master/server logRouter.get("/loggate/v1/listall", function(req, res) { let ...

Display the JSON data in a table by utilizing the ng-repeat directive in Angular

Below is the response that I have: Response : response: {"json": {"response": {"servicetype":"", "functiontype":"", "statuscode":"0", "statusmessage":"Success", "data":[{"graphtype":"piechart", "xlabel":"state", "ylabel":"count", "s1":"contact", "s2":" ...

In my experience, Angular will generate an error if a form tag in HTML contains special characters, such as the colon symbol ':' in the 'name' attribute

Currently, I am in the midst of a Salesforce project and I am contemplating utilizing Angular JS for its remarkable capabilities. One issue I have encountered is that Salesforce prefixes form attributes like name and id with dynamic IDs. For example, if th ...

Error encountered in Django due to improperly formatted JSON data

Whenever I manually input the data into a POST request, I encounter an error. However, when I use the admin page to do so, there is no issue. The error seems to be with the "contact_number" field. Here is the correct format for adding data in the admin pa ...

Troubleshooting Problems with Ajax Servlets

When I perform a search, the results are returned and shortly after, the page redirects to a servlet displaying raw JSON data. It's a bit confusing for me. This JSP form submission: <form class="col-lg-12" action="./urllinks" method="GET" id="sea ...

Adjusting height in Google Maps to fill the remaining space

Currently, I am developing a map application where I want the Google Maps DIV to occupy the remaining height under the header. Here is the code snippet: <!DOCTYPE html> <head> <title>Map Application</title> <style type ...

Utilizing Vue and Nuxt to Filter JSON Data by Category using Content Api

Currently, I'm working on assembling a portfolio within the Nuxt framework. The portfolio's content is sourced from GoogleSheets, and using the GoogleSheets API, I created a portfolio.json file stored in the Nuxt/Content directory. So far, I have ...

Creating a personalized image download feature in PhotoSwipe.js

I am currently working on a project that involves using the PhotoSwipe gallery. At line 175, there is code url:items[0].hqImage. I want to use the index of the current image instead of 0. How can I achieve this? I attempted to utilize the pswp.listen(&ap ...

Preserving intricate nesting in a Mongoose schema

I've encountered a problem when trying to save nested subdocuments - I'm not certain if it's because they're not in an array or some other reason. The docs suggest that nested objects should be auto-saved, but that doesn't seem to ...

What are the steps to integrate dynamic data into chartjs?

Can you assist me in understanding how to dynamically populate Chartjs with data from a json file? Specifically, I am looking to dynamically fill the labels and data fields. Sample JSON File <<< [ { "EFICAZ_TAB_ITEM_ID":1, " ...

Date selection feature in Material UI causing application malfunction when using defaultValue attribute with Typescript

Recently, I discovered the amazing functionality of the Material UI library and decided to try out their date pickers. Everything seemed fine at first, but now I'm facing an issue that has left me puzzled. Below is a snippet of my code (which closely ...

``There Seems to be an Issue with Loading Content in Tabs

Hey! I'm encountering an issue with my jquery tabs. The first tab content loads fine, but when I select another tab, the content doesn't display. Then, when I try to go back to the first tab, it doesn't load either. Here's the HTML cod ...

Ways to retrieve the identifier of the uploaded document in GridFs for linking with another model

After creating a GridFS and uploading an image using the code snippet below: app.post("/upload", upload.single("photo"), function(req, res) { res.redirect("/images"); }) I also have a separate model for users: var userSchema = new mongoose.Schema({ ...

The converted document exported using threejs-usdzExporter does not appear correctly on an iPhone

I loaded a glb file using THREE.js GLTFLoader and then exported it to usdz using USDZ Exporter. When I tried to open it in the browser, it showed up in Safari but didn't appear in ARkit in object mode. Instead, it appeared above my head in AR mode. Th ...

Click on an Object within a modal window using JavaScript in Internet Explorer 8

I'm facing a strange issue with the SELECT object in a Modal Window. Within my HTML code, I have a button that opens a modal window when clicked. Inside this modal window, a JSP page is loaded. On this JSP page, there is a dropdown list created using ...