Last active
June 15, 2018 05:11
-
-
Save kejun/d6e4a5380a0d84f04f4f0623e14768e5 to your computer and use it in GitHub Desktop.
两个圆连线的切点
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* r: circle -> r, ellipse -> rx, ry | |
*/ | |
export const getCenterPoint = (x, y, r) => (r.rx ? { | |
x: x + r.rx, | |
y: y + r.ry, | |
rx: r.rx, | |
ry: r.ry, | |
} : { | |
x: x + r, | |
y: y + r, | |
r: r, | |
}); | |
export const getCircleTangentPoint = (from, to) => { | |
var { x: fromX, y: fromY } = from; | |
var { x: toX, y: toY, r } = to; | |
var theta; | |
var x; | |
var y; | |
if (fromY > toY) { | |
theta = Math.atan2(fromX - toX, fromY - toY); | |
y = Math.cos(theta) * r; | |
x = Math.sin(theta) * r; | |
} else { | |
theta = Math.atan2(fromY - toY, fromX - toX); | |
x = Math.cos(theta) * r; | |
y = Math.sin(theta) * r; | |
} | |
return { | |
x: toX + x, | |
y: toY + y, | |
}; | |
}; | |
export const getEllipseTangentPoint = (from, to) => { | |
var { x: fromX, y: fromY } = from; | |
var { x: toX, y: toY, rx, ry } = to; | |
var x; | |
var y; | |
var distX; | |
var distY; | |
var g; | |
distX = fromX - toX; | |
distY = fromY - toY; | |
g = distY / distX; | |
x = (fromX < toX ? -1 : 1) * rx * ry / Math.sqrt(ry * ry + g * g * rx * rx); | |
y = g * x; | |
return { | |
x: toX + x, | |
y: toY + y, | |
}; | |
}; | |
export const getTangentPoints = ([x1, y1, x2, y2, r1, r2, tension=30]) => { | |
// p1 ---> p2 | |
var p1 = typeof r1 === 'object' ? | |
getEllipseTangentPoint({ | |
...getCenterPoint(x2, y2, r2), | |
}, { | |
...getCenterPoint(x1, y1, r1), | |
}) : getCircleTangentPoint({ | |
...getCenterPoint(x2, y2, r2), | |
}, { | |
...getCenterPoint(x1, y1, r1), | |
}); | |
var p2 = typeof r2 === 'object' ? | |
getEllipseTangentPoint({ | |
...getCenterPoint(x1, y1, r1) | |
}, { | |
...getCenterPoint(x2, y2, r2) | |
}) : getCircleTangentPoint({ | |
...getCenterPoint(x1, y1, r1) | |
}, { | |
...getCenterPoint(x2, y2, r2) | |
}); | |
var dx = (p1.x + p2.x) / 2; | |
var dy = (p1.y + p2.y) / 2; | |
var dist = ((x, y) => Math.sqrt(x * x + y * y)) | |
(Math.abs(p1.x - p2.x), Math.abs(p1.y - p2.y)); | |
dx = dx + dist / tension; | |
dy = dy - dist / tension; | |
return [p1.x, p1.y, dx, dy, p2.x, p2.y]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment