如何查找用于在饼图上创建标签的 X Y 坐标 (ReactJS)



我需要一些帮助才能越过终点线。我正在从头开始创建一个饼图,因为我们不允许使用任何库。我开始创建图表,但是我不知道如何为标签获取正确的 X 和 Y 坐标。我确信涉及一些计算,但我似乎无法找出正确的计算。

我有一个jsFiddle,上面有我的代码,目前我随机化了X和Y坐标以在任何地方显示Test。我想知道如何将其添加到正确的名称中。

https://jsfiddle.net/v9ex8zwh/

let slices = [
{percent: 0.7307692307692307, color: "green", asset_type: "Multifamily"},
{percent: 0.07692307692307693, color: "red", asset_type: "Industrial"}, 
{percent: 0.07692307692307693, color: "yellow", asset_type: "Special Purpose"}, 
{percent: 0.07692307692307693, color: "grey", asset_type: "Vacant Land"},
{percent: 0.038461538461538464, color: "blue", asset_type: "Mixed Use"}
]

class PieChart extends React.Component{
constructor(props) {
super(props)
}
render() {
let viewBox=` -${this.props.width} -${this.props.width} ${this.props.width*2} ${this.props.width*2}`
let transform = "rotate(0 0 0)"; //if you want it rotated a certain angle change the first number in the this transform object
return (
<div>
<div>
<svg width={this.props.width} height={this.props.width} viewBox={viewBox} transform = {transform}>
{getPaths(this.props.slices, this.props.width)}hello
</svg>
</div>
</div>
);
}
}
function getCoordinatesForPercent(percent) {
const x = Math.cos(2 * Math.PI * percent);
const y = Math.sin(2 * Math.PI * percent);
return [x, y];
}
let cumulativePercent = 0;
const getPaths = (slices, size) => {
let paths = [];
slices.forEach(slice => {
let [startX, startY] = getCoordinatesForPercent(cumulativePercent);
cumulativePercent += slice.percent;
const [endX, endY] = getCoordinatesForPercent(cumulativePercent);
// if the slice is more than 50%, take the large arc (the long way around)
const largeArcFlag = slice.percent > .5 ? 1 : 0;
// create an array and join it just for code readability
const pathData = [
`M ${startX * size} ${startY * size}`, // Move
`A ${size} ${size} 0 ${largeArcFlag} 1 ${endX * size} ${endY * size}`, // Arc (size is same as radius)
`L 0 0`, // Line
].join(' ');
paths.push(<g overflow='hidden'><path d={pathData} stroke={'rgba(0, 0, 0, 1)'} fill={slice.color}/><text x={(Math.random() * 70)} y ={(Math.random() * 120)}> + Test</text></g>)
});
return paths;
}
ReactDOM.render(<PieChart slices={slices} width={250}/>, document.querySelector("#app"))

您可以使用鼠标事件来查找。

a POC:

const circ = document.querySelector('.circ');
const x = document.querySelector('.x');
const y = document.querySelector('.y');
circ.addEventListener("mousemove", (e) => {
x.innerHTML = 'x: ' + e.offsetX;
y.innerHTML = 'y: ' + e.offsetY;
});
.circ {
margin: 20px auto 0 auto;
height: 100px;
width: 100px;
background: red;
border-radius: 50%;
}
<div class="circ"></div>
<div class="x"></div>
<div class="y"></div>

最新更新