css - 旋转不在其位置旋转
问题描述
我正在尝试实现这个 Piechart,但我想在不旋转的情况下旋转它,然后将其文本重新旋转为水平。问题是它没有在它的位置居中。我试图改变原点中心。
这是我的代码:
const data= [
{
name: props.language == "CP",
value: 300
},
{
name: props.language == "CP",
value: 300
}
];
const RADIAN = Math.PI / 180;
const renderCustomizedLabel = ({
cx,
cy,
midAngle,
innerRadius,
outerRadius,
percent,
index,
name
}) => {
const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
const x = cx + radius * Math.cos(-midAngle * RADIAN);
const y = cy + radius * Math.sin(-midAngle * RADIAN);
console.log(cx, cy, midAngle, innerRadius, outerRadius, RADIAN, radius);
return (
<text
style={{ WebkitTransform: "rotate(90deg)", transformOrigin: "center" }}
x={x}
y={y}
fill="white"
textAnchor={x > cx ? "start" : "end"}
dominantBaseline="central"
>
{name}
</text>
);
};
<div style={{ width: "100%", height: 310 }} className="rotate">
<ResponsiveContainer>
<PieChart>
<Pie
data={data}
labelLine={false}
label={renderCustomizedLabel}
fill="#0eb89a"
dataKey="value"
/>
</PieChart>
</ResponsiveContainer>
CSS:
.rotate {
background-color: transparent;
transform: rotate(270deg);
margin: auto;
}
解决方案
我会使用 svgtransform
文本节点,而不是使用x
和y
属性来定位它们。
const { PieChart, Pie, Sector, Cell } = Recharts;
const data = [{name: 'Group A', value: 400}, {name: 'Group B', value: 300},
{name: 'Group C', value: 300}, {name: 'Group D', value: 200}];
const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];
const RADIAN = Math.PI / 180;
const renderCustomizedLabel = ({ cx, cy, midAngle, innerRadius, outerRadius, percent, index }) => {
const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
const x = cx + radius * Math.cos(-midAngle * RADIAN);
const y = cy + radius * Math.sin(-midAngle * RADIAN);
return (
<text transform={`translate(${x},${y}) rotate(45)`} fill="white" textAnchor={`middle`} dominantBaseline="central">
{`${(percent * 100).toFixed(0)}%`}
</text>
);
};
const SimplePieChart = React.createClass({
render () {
return (
<PieChart width={800} height={400} onMouseEnter={this.onPieEnter}>
<Pie
data={data}
cx={300}
cy={200}
labelLine={false}
label={renderCustomizedLabel}
outerRadius={80}
fill="#8884d8"
>
{
data.map((entry, index) => <Cell fill={COLORS[index % COLORS.length]}/>)
}
</Pie>
</PieChart>
);
}
})
ReactDOM.render(
<SimplePieChart />,
document.getElementById('container')
);
推荐阅读
- typescript - Typescript:为文件中的所有函数声明 ReturnType(如何创建 redux 操作类型)
- javascript - 运行图像组合过滤器引导代码时的 Javascript 问题
- angular - 材料对话框测试数据未进入我的对话框
- ruby-on-rails - NS-Vue/Rails 对 S3 存储桶的预签名 PUT 请求给出 403
- python - 塞萨尔密码
- c# - 试图实施一波又一波的敌人
- javascript - 如何以简单的形式限制密码尝试次数?
- c++ - 如何在 C++ 中插入 protobuf 映射?
- javascript - 有没有办法从一个类中获取所有新值?
- javascript - 我们可以在控制台中使用全局变量做什么?