生成随机坐标,存储在圆半径内

时间:2018-11-06 14:55:06

标签: javascript reactjs

我有一个公式,该公式生成需要在网格上显示的数字。所有的点都应该从原点开始向各个方向扩展。

这些应该随机扩展到所有面,但是,由于公式随时间变化,因此显示的点越来越多。

比方说,我们有100分,我们已经将其设置在网格上,更新了公式,并且有150分。图只能更新50个新图。

在React JavaScript中有什么方法可以做到这一点吗?

下面是Java中的一种试验,它不存储数字,只是形象地显示。

public void getRandomPointInCircle() {
    double t = 2 * Math.PI * Math.random();
    double r = Math.sqrt(Math.random());
    double x = r * Math.cos(t);
    double y = r * Math.sin(t);
    System.out.println(x);
    System.out.println(y);
}

Circle - Trial 2

2 个答案:

答案 0 :(得分:3)

反应可能特别适合此任务。运行下面的代码片段以查看其工作。

确保反应仅渲染新元素的技巧是在每个渲染的圆上使用唯一的key道具。不变的密钥不会重新呈现。

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      points: []
    };
  }

  getRandomPointInCircle() {
    const t = 2 * Math.PI * Math.random();
    const r = Math.sqrt(Math.random());
    const cx = r * Math.cos(t);
    const cy = r * Math.sin(t);
    const fill = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
    return {cx, cy, fill, r:"0.02"};
  }
  addPoints = () => {
    const points = this.state.points.concat(
      new Array(20).fill().map(p => this.getRandomPointInCircle())
    );
    this.setState({points})
  }

  render() {
    const {points} = this.state;
    return (
      <div>
      <button onClick={this.addPoints}>Add 20 points</button><br/>
        <svg style={{overflow:'visible'}} height="200px" viewBox="-1 -1 2 2">
          <rect width="2" height="2" x="-1" y="-1" fill="#efefef" />
          <circle cx={0} cy={0}r={1} fill="#ffffff" />
          {points.map((p,index)=>(
            <circle
              key={`${p.x}-${p.y}-${index}`}
              {...p}
            />
          ))}
        </svg>
      </div>
    );
  }
}

// Render it
ReactDOM.render(
  <App />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="react"></div>

答案 1 :(得分:1)

我认为您在这里看到的是一个有状态的组件(React擅长处理该组件)。该组件可以存储点数和每个位置中的每一个,每次添加新点时,都将使用新状态调用设置状态方法,新状态将是前一个状态加上新的点。

class Circle extends React.Component {

  constructor(props) {
    this.state = {points : [], npoints : 0}
  }

  render() {
    return (
      <div className="circle">... implement this render view ...
        <Points data={this.state.points}></Points>
      </div>
    );
  }

  addNewPoints(){
    let newPoints = [...this.state.points];
    newPoints.push(this.generateNewPoints());
    newState = {points :newPoints , npoints : newPoints.length}
    this.setState(newState);
  } 

  generateNewPoints(){
    //getRandomPointInCircle ...
  }

}
相关问题