如果 React.js 中的圆圈,则尝试绘制相等的扇区。我的 pathData 或我的数学有什么不正确的地方吗?

问题描述 投票:0回答:0

我正在尝试使用

<svg>
<path>
元素绘制圆的等扇区。我做了一些搜索,以找到有关如何在给定您正在移动的扇区的半径和角度的情况下计算圆周上的点坐标的数学方法,我在 here 中找到了一个很好的答案。我稍微修改了它以使用“圆周百分比”,它基本上只是总结了以前的扇区角度。

在查看呈现的页面时,我正在计算的 x 和 y 坐标看起来好像不正确,但是使用

console.log()
显示值是正确的并且与我手工完成的匹配(当然是使用计算器).

这是我的 React 组件代码:

export default function CircleEqualSectors({ radius, numSectors }) {

  const diameter = radius * 2

  /* Using 2Pi Radians here, not 360 degrees */
  function getCoordinatesForPercent(percent) {
    const x = Math.cos(2 * Math.PI * percent) * radius
    const y = Math.sin(2 * Math.PI * percent) * radius
    return [x, y]
  }

  var sectors = []
  let cumulativePercent = 0
  const percentRoundCircle = 1 / numSectors
  for (let i = 0; i < numSectors; i++) {
    const [startX, startY] = getCoordinatesForPercent(cumulativePercent)
    cumulativePercent += percentRoundCircle
    const [endX, endY] = getCoordinatesForPercent(cumulativePercent)

    const xAxisRotation = 0
    const largeArcFlag = percentRoundCircle > 0.5 ? 1 : 0
    const sweepFlag = 0
    const pathData = [
      `M ${radius} ${radius}`, /* Move to centre of circle */
      `L ${startX} ${startY}`, /* Draw line to first point */ 
      `A ${radius} ${radius} ${xAxisRotation} ${largeArcFlag} ${sweepFlag} ${endX} ${endY}`, /* Draw arc to next point */
      `L ${radius} ${radius}` /* Draw line back to centre of circle */
    ].join(' ')
    sectors.push({ key: i, pathData: pathData })
  }

  console.log(sectors)

  return (
    <div>
      <svg height={diameter} width={diameter}>
        <circle r={radius} cx={radius} cy={radius} fill="grey"/>
        <path d={sectors[0].pathData} stroke="red"/>
        <path d={sectors[1].pathData} stroke="red"/>
        <path d={sectors[2].pathData} stroke="red"/>
        <path d={sectors[3].pathData} stroke="red"/>
        <path d={sectors[4].pathData} stroke="red"/>
        <path d={sectors[5].pathData} stroke="red"/>
        <path d={sectors[6].pathData} stroke="red"/>
        <path d={sectors[7].pathData} stroke="red"/>
        <path d={sectors[8].pathData} stroke="red"/>
        <path d={sectors[9].pathData} stroke="red"/>
        <path d={sectors[10].pathData} stroke="red"/>
        <path d={sectors[11].pathData} stroke="red"/>
        {/* {sectors.map((sector) => {
          <path d={sector.pathData} stroke="red"/>
        })} */}
      </svg>
    </div>
  )

使用上面的代码,只渲染单个扇区以查看其奇怪的形状。看起来“最正确”的扇区是

sector[1]
,但仍然没有达到圆的整个半径。我真的不太确定这里有什么不正确,因为我自己计算了坐标并将它们打印到控制台并且它们匹配。

我使用这个文档来了解如何在

Arc
中使用
<path>

命令
javascript reactjs math geometry
© www.soinside.com 2019 - 2024. All rights reserved.