[英]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. 假设我有两点:x1,y1和x2,y2。 in a line like below: 如下所示:
x1,y1 is A. x2,y2 is B. x1,y1是A. x2,y2是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. 我试着写一个函数,我可以在上面的图像中提供距离(-1或1),它返回x和y坐标。 This way i can add a middle point in the path to render the line the below: 这样我可以在路径中添加一个中间点来渲染下面的行:
[update] [更新]
You have to use the angle of the line figure out x and y im looking for. 你必须使用x和y im寻找的线条图的角度。 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. 下面显示的是45度线,三角形的一边是5,一边是1.从那里,你可以计算x和y。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.