Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 find the angle of line

Tags:

d3.js

I have x1,y1,x2,y2, how do I calculate the angle of this line?

Do I have to use pure math? or there is something in d3 to help me?

            edgeContainer.append("g")
                .selectAll("path")
                .data(edges)
                .enter()
                .append("path")
                .attr("class", function (d) {
                    return "nodeLine animate nodeLine_" + NodeUtils.createEdgeClass(d) + " node_" + d.outV + " node_" + d.inV;
                })
                .style("fill", "none")
                .style(edgeType == 'circular' ? "marker-start" : "marker-end", "url(#arrow)")
                .style("stroke", function (d) {
                    return options.edgeStroke ? options.edgeStroke : ReferenceData.getByRelationshipType(d.label).stroke;
                })
                .style("stroke-dasharray", function (d) {
                    return options.edgeStrokeDasharray ? (options.edgeStrokeDasharray == 'none' ? false : options.edgeStrokeDasharray) : ReferenceData.getByRelationshipType(d.label)['stroke-dasharray'];
                })
                .attr("d", function (d, i) {
                    var x1 = d.targetNode.node.x;
                    var y1 = d.targetNode.node.y;
                    var x2 = d.sourceNode.node.x;
                    var y2 = d.sourceNode.node.y;
                })

            ;
like image 257
Aladdin Mhemed Avatar asked Oct 19 '25 17:10

Aladdin Mhemed


1 Answers

Calculation of the angle is easy:

 var angle = Math.atan2(y2 - y1, x2 - x1));

If you need degrees, you can easily convert it by multiplying it with 180/pi.

The Math.atan2() method returns a numeric value between -π and π representing the angle theta of an (x, y) point. This is the counterclockwise angle, measured in radians, between the positive X axis, and the point (x, y). Note that the arguments to this function pass the y-coordinate first and the x-coordinate second.

enter image description here

Documentation: developer.mozilla.org - Math.atan2()

like image 87
Ctx Avatar answered Oct 22 '25 06:10

Ctx