Determine the central point between two nodes, then sketch a line at a 90-degree angle extending from it to create a new node

Imagine in d3 there are two nodes, node1 and node2, depicted as circles positioned next to each other horizontally. These nodes are connected by a short horizontal line (represented as a path).

I am curious about how to: (1) determine the midpoint of that connecting line/path, (2) assign a new identifier or name to that midpoint for programmable manipulation, (3) create new vertical lines/paths extending from that midpoint to additional nodes such as node3, node4, and node5.

Answer №1

To create connections between nodes, you can calculate the midpoint of each line and draw lines from that point to other nodes using the following script. Check out this JSFiddle for a live demo.

function establishConnections(d){
    var xStart = nodes[d.source].x;
    var xEnd = nodes[d.target].x;
    var yStart = nodes[d.source].y;
    var yEnd = nodes[d.target].y;
    var otherNodes = nodes.filter(function(n,i){ return i!=d.source || i!=d.target });
    otherNodes.forEach(function(otherNode){
         svg.append("line")
            .attr("x1",function(d){ return otherNode.x; })
            .attr("y1",function(d){ return otherNode.y; })
            .attr("x2",function(d){ return (xStart + xEnd)/2; })
            .attr("y2",function(d){ return (yStart + yEnd)/2; })
            .attr("class","connection-line");
    });

}
linksEls.each(establishConnections);

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

Verify for a class that does not exist

I am working on a script that updates the content of a div and increments its value by 1 $(function() { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'), }, }); ...

The Ajax request encountered a syntax error due to an unexpected token '<'

I have searched the forum extensively for similar questions, but unfortunately haven't found a suitable answer for my specific problem. In my jQuery code, I am attempting to make an AJAX call using the following snippet: function submitForm(formData) ...

Struggling with defining the default value for a JavaScript array

One interesting feature on my website is a changing h1 heading that updates when the user clicks a button. However, I encountered an issue where, upon initial page load, the h1 appears empty and only populates with text after the button is clicked. I am ...

There is no output generated by Node.js express

I have encountered an issue where moving app.listen to the top results in a port in use error. I suspect this is because my websocket setup is using the same port, but I'm unsure how to resolve this. var server = require('websocket').server ...

Is there a way to attach an event listener to a span that was inserted using DTColumnBuilder?

I am attempting to include an onclick event for a span element that is generated by DTColumnBuilder. DTColumnBuilder .newColumn('Invoice') .withTitle('<span class="li-table-head ...

In React, the ES6 prototype method map failed to render anything on the screen

Is there an issue with my map method implementation? var App = React.createClass({ getInitialState(){ return { items:[1,2,3] } }, renderItem(){ return( this.state.items.map((item,i))=> <li key={i}> { ...

Preserve user-inputted text from jQuery within a div container

With the help of the knowledgeable individuals here, I successfully created a prototype to address an issue I had encountered. The problem involved using a textbox input with a password requirement to update an HTML element. Although everything is functio ...

The Bootstrap Tooltip seems to be glued in place

Utilizing jQuery, I am dynamically generating a div that includes add and close buttons. Bootstrap tooltips are applied to these buttons for additional functionality. However, a problem arises where the tooltip for the first add button remains visible even ...

Using the "push" method to create an array of objects in Javascript

I am relatively new to Javascript and I've encountered an issue in my code that I can't quite figure out. My objective is to build an array of "people" where each person has specific information such as an "id" and a "name". Since I don't k ...

Dynamic translation using Angular 6's i18n functionality

I'm working on translating a piece of code using Angular's i18n. Everything seems to be in order, but I'm facing a challenge with translating the words 'Enable' or 'Disable' based on the dynamic status of the item. The se ...

Commitment without anticipation of a resolution or rejection

While testing one of my AngularJs Services, I decided to write some Unit tests. Below is a sample code snippet that I have come up with: it('', function(done) { aDocument.retrieveServiceFile(extractedFileFeature) .then(function() { ...

The function .remove() fails to remove a text node in Internet Explorer

Check out the code here: http://jsfiddle.net/6nN7G/ Utilizing a shopify app for star reviews that generates div.text - my aim is to eliminate the text indicating the number of reviews such as "19 reviews" and "3 reviews" from the HTML. This action is perf ...

Using AngularJS to access form field ids that are generated dynamically

I am dynamically generating form fields using ng-repeat and everything is functioning correctly. However, I now want to incorporate an angular datepicker component that is based on a directive. The issue I am facing is that it only seems to work with stat ...

Encountering a script error that reads "TypeError: $ is not defined as a function

I am attempting to send an email using web services in asp.net, utilizing html and sending the information through a jquery ajax function. Below is the html form: <div class="col-md-6"> <h2>DROP ME A LINE</h2> & ...

Ending a session in Node.js with Express and Socket.io

I've been grappling with this issue for a few days now and I'm just not able to wrap my head around it. I need to end my session when I navigate away from the webpage, but the error message I keep receiving (which ultimately crashes the server) r ...

Exploring audio analysis across different platforms using the power of the Web Audio API

Currently, I am in the process of developing an audio visualizer application using the web audio api and the three.js library. Utilizing the html5 element has been effective in extracting audio from local mp3 files or streaming mp3 files through the crea ...

Tips for creating AngularJS forms which display radio buttons and populate data from a JSON file

I'm having trouble displaying the json data correctly. How can I show the radio buttons from my json file (plunker demo)? Additionally, I want to validate the form when it is submitted. Here is the HTML code: <my-form ng-app="CreateApp" ng- ...

JavaScript - AngularJS HTML parser

I am working with an array that contains content along with HTML tags, and here is the code snippet: for (car in cars.parking[0]){ content.push('<br />'); for (token in cars.parking[0].now) { content.pus ...

Efficient - Managing numerous database connections

I am currently working on a project using node.js and I have created a login form where users need to select the database they want to connect to. However, I am uncertain about how to establish a connection with the selected database. Is there a way for m ...

Issues with NuxtJs dynamic open graph tags are causing errors

i am currently working on implementing dynamic open graph meta tags using this code snippet async asyncData({ app, route }) { let postDetails = await app.$axios.get(`/api/v1/news/single/${route.params.id}`); postDetails = postDetails.da ...