Calculate Wheel Data XY Position

2020-07-22 17:19发布

问题:

I tried to create a lucky draw wheel using reactjs, first, I need to place all the input data to a certain XY position. Below is the expected output XY position example what I need.

var renderData = ["1","2","3","4","5","6","7","8","9","10","11","12"];
React.createElement('div', { className: '_data'},
    renderData.map((index,item)=>{
        var itemPosition = index / renderData.length * 360;
        var itemX = itemPosition * Math.PI/180;
        var itemY = itemPosition * Math.PI/180;
        return React.createElement('div', { className: '_items',
            style:{top:itemX,left:itemY}
        },item);
    })
)

So I use createElement to create div for each of the data, then using top and left for XY position.

How to calculate the XY position for each div

Update

After tried the @keikai answer

var renderData = ["1","2","3","4","5","6","7","8","9","10","11","12"];
const r = 350;
const len = renderData.length;
const radiusList = renderData.map(x => (360 / len) * (x - 1));
const positionPairList = radiusList.map(x => ({
        x: Math.sin((Math.PI * x) / 180) * r,
        y: Math.cos((Math.PI * x) / 180) * r
}));
React.createElement('div', { className: '_data'},
    renderData.map((item, index) => {
        return React.createElement('div', { className: `_items`,
            style:{top:`${positionPairList[index].x.toFixed(2)}px`,left:`${positionPairList[index].y.toFixed(2)}px`}
        },item);
    })
)

  1. all data are rotated 0deg
  2. child div still not place to the right position inside parent div
  3. for clockwise, it starts from 10?

回答1:

Update: rotate display with clock styles

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";

function App() {
  const n = 12;
  const r = 500;

  const radiusList = Array.from(Array(n).keys()).map(x => (360 / n) * x);
  const positionPairList = radiusList.map(item => ({
    x: Math.sin((Math.PI * item) / 180) * r,
    y: Math.cos((Math.PI * item) / 180) * r
  }));
  return (
    <div className="App">
      {positionPairList.map((item, index) => {
        const offset = index === 0 ? n : 0;
        return (
          <div
            className="Parts"
            style={{
              top: `${r - item.y.toFixed(0)}px`,
              right: `${r + 200 - item.x.toFixed(0)}px`,
              transform: `rotate(${radiusList[index]}deg)`
            }}
          >
            {index + offset}
          </div>
        );
      })}
    </div>
  );
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);