Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculating the arc/point in d3 path

I'm struggling to figure out the correct geometry for finding a mid point of a path along an arc. Lets say i have two points: x1,y1 and x2, y2. in a line like below:

arc

x1,y1 is A. x2,y2 is B.

Im trying to write a function that i can supply the distance (-1, or 1) in the above image and it returns the x and y coords. This way i can add a middle point in the path to render the line the below:

arc

[update]

You have to use the angle of the line figure out x and y im looking for. Below is showing that the line is 45 degres, one side of the triangle is 5, one side is 1. From that, you can calculate x and y.

arc

I think i figured it out with the code below and fiddle fiddle example:

var svgContainer = d3.select("#canvas").append("svg")
                                       .attr("width", 400)
                                       .attr("height", 400);

var lineData = [ { "x": 0,   "y": 0},  { "x": 100,  "y": 100}];

var midPoint = {
    x:Math.abs(lineData[1].x - lineData[0].x)/2,
    y:Math.abs(lineData[1].x - lineData[0].x)/2
};

function calcAngle(x1, x2, y1, y2) {
    var calcAngleVal = Math.atan2(x1-x2,y1-y2)*(180/Math.PI);

    if (calcAngleVal < 0) {
        calcAngleVal = Math.abs(calcAngleVal);
    } else{
        calcAngleVal = 360 - calcAngleVal;
    }

    return calcAngleVal;
}

var angle = calcAngle(lineData[0].x, lineData[1].x,lineData[0].y,lineData[1].y);


var sin = Math.sin(angle * Math.PI / 180);
var cos = Math.cos(angle * Math.PI / 180);

var xLen = Math.abs(lineData[1].x - lineData[0].x)/2;
var yLen = Math.abs(lineData[1].y - lineData[0].y)/2;


var n = 1.5;

var midpointArc = {
    x: midPoint.x + (sin * (n * 25)),
    y: midPoint.y + (cos * (n * 25)) 
 };

lineData.splice(1,0,midpointArc);

var lineFunction = d3.svg.line()
                         .x(function(d) { return d.x; })
                         .y(function(d) { return d.y; })
                         .interpolate("basis");

var lineGraph = svgContainer.append("path")
                            .attr("d", lineFunction(lineData))
                            .attr("stroke", "blue")
                            .attr("stroke-width", 1)
                            .attr("fill", "none");

var pathEl   = lineGraph.node();
var curvedMidpoint = pathEl.getPointAtLength(pathEl.getTotalLength()/2);

svgContainer.append("circle")
            .attr('r',5)
            .attr('cx', curvedMidpoint.x)
            .attr('cy', curvedMidpoint.y)
like image 695
jamescharlesworth Avatar asked Sep 05 '13 02:09

jamescharlesworth


1 Answers

To find the midpoint of any path (not just an arc):

var pathEl   = d3.select('#pathId').node();
var midpoint = pathEl.getPointAtLength(pathEl.getTotalLength()/2);

adapted from Duopixel's answer and bl.ockus.

like image 177
Adam Pearce Avatar answered Oct 19 '22 12:10

Adam Pearce