Public
Edited
Nov 11, 2022
4 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function computeLabelPlacement(
pos, // the circle's center
r, // the circle's radius
a, // the angle of the direction by which to displace the label from the circle's center
max, // the maximum allowed horizontal displacement of the label's center from the circle's center
fontSize // the label's font size
) {
// the text-anchor and dy we'll need in order to achieve the displacement we want
let anchor = 'middle'
let dy = fontSize / 3

// how far away to displace the label's bbox's closest edge from the circle's center
let distance = (r + dy) / Math.abs(Math.sin(a))

if (Math.abs(distance / Math.sin(a)) > max) {
// if Max X Displacement is exceeded, anchor to either the start or end of the text
anchor = Math.cos(a) < 0 ? 'end' : 'start'
dy = fontSize / 3 + Math.sin(a) * fontSize / 3
distance = r
}

// Finally, compute the target point at which we want the text to be positioned
pos = [pos[0] + Math.cos(a) * distance, pos[1] + Math.sin(a) * distance]

return { pos, anchor, dy }
}
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more