【发布时间】:2020-05-16 07:24:37
【问题描述】:
我需要一些帮助才能越过终点线。我正在从头开始创建一个饼图,因为我们不允许使用任何库。我开始创建图表,但是我不知道如何为标签获取正确的 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"))
【问题讨论】:
-
我认为您的 jsfiddle 与您在此处的代码不匹配。另外,一点提示,您可以在渲染中将
width声明为变量,然后您不必编写this.props.width十次。也就是在你的渲染函数中写入const { width } = this.props;,然后使用width。 -
我将发布的代码复制到了一个新的 jsFiddle(使用 React)中,它显示了相同的结果,看起来很奇怪。至于 { width } 的事情,谢谢。我正在研究别人的例子,并没有费心改变他们的代码。
标签: html css reactjs svg charts