我有一个公式可以生成需要在网格上显示的数字。所有的点都应该从原点开始,均匀地向四面八方扩展。
这些应该是随机向四面八方扩展的,但是,因为公式随着时间的推移而变化,所以要显示的点越来越多。
假设我们有 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);
}
最佳答案
React 可能特别适合这项任务。运行下面的代码片段以查看其工作情况。
确保 React 只渲染新元素的技巧是在每个渲染的圆圈上使用唯一的 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>
关于javascript - 生成随机坐标,存储在圆半径内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53174387/