mirror of
https://github.com/mermaid-js/mermaid.git
synced 2025-09-02 15:16:49 +02:00
#945 Rendering of labels and new label positioning algorithm
This commit is contained in:
50
src/utils.js
50
src/utils.js
@@ -73,8 +73,56 @@ export const interpolateToCurve = (interpolate, defaultCurve) => {
|
||||
return d3[curveName] || defaultCurve;
|
||||
};
|
||||
|
||||
const distance = (p1, p2) =>
|
||||
p1 && p2 ? Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2)) : 0;
|
||||
|
||||
const traverseEdge = points => {
|
||||
let prevPoint;
|
||||
let totalDistance = 0;
|
||||
|
||||
points.forEach(point => {
|
||||
totalDistance += distance(point, prevPoint);
|
||||
prevPoint = point;
|
||||
});
|
||||
|
||||
// Traverse half of total distance along points
|
||||
const distanceToLabel = totalDistance / 2;
|
||||
|
||||
let remainingDistance = distanceToLabel;
|
||||
let center;
|
||||
prevPoint = undefined;
|
||||
points.forEach(point => {
|
||||
if (prevPoint && !center) {
|
||||
const vectorDistance = distance(point, prevPoint);
|
||||
if (vectorDistance < remainingDistance) {
|
||||
remainingDistance -= vectorDistance;
|
||||
} else {
|
||||
// The point is remainingDistance from prevPoint in the vector between prevPoint and point
|
||||
// Calculate the coordinates
|
||||
const distanceRatio = remainingDistance / vectorDistance;
|
||||
if (distanceRatio <= 0) center = prevPoint;
|
||||
if (distanceRatio >= 1) center = { x: point.x, y: point.y };
|
||||
if (distanceRatio > 0 && distanceRatio < 1) {
|
||||
center = {
|
||||
x: (1 - distanceRatio) * prevPoint.x + distanceRatio * point.x,
|
||||
y: (1 - distanceRatio) * prevPoint.y + distanceRatio * point.y
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
prevPoint = point;
|
||||
});
|
||||
return center;
|
||||
};
|
||||
|
||||
const calcLabelPosition = points => {
|
||||
const p = traverseEdge(points);
|
||||
return p;
|
||||
};
|
||||
|
||||
export default {
|
||||
detectType,
|
||||
isSubstringInArray,
|
||||
interpolateToCurve
|
||||
interpolateToCurve,
|
||||
calcLabelPosition
|
||||
};
|
||||
|
Reference in New Issue
Block a user