gpt4 book ai didi

javascript - 将点均匀分布在圆上

转载 作者:行者123 更新时间:2023-11-30 11:36:05 27 4
gpt4 key购买 nike

我需要将点均匀分布在圆的圆周上,但我已经失去了理智。结果并不完全是圆形的,而是螺旋形的,尤其是在点数较多的情况下。我已经进行了大力研究,但仍然无法找出哪里可能出错。

  window.onload = function() {
var num = 15;

var angle = (2 * Math.PI)/(num+1); var count = 0;
var demo = document.getElementById("demo");

function Dot() {
this.angle = angle * count;
count++;
this.x = Math.cos(this.angle) * 200;
this.y = Math.sin(this.angle) * 200;
}

Dot.prototype.create = function() {
var dot = document.createElement("div");
dot.style.top = this.y + 100 + "px";
dot.style.left = this.x + 200 + "px";
dot.className = "dot";
demo.appendChild(dot);
}

for (var i = 0; i < num; i++) {
var d = new Dot();
d.create();
}
}
  .dot {
height: 20px;
width: 20px;
border-radius: 50%;
background: blue;
position: relative;
text-align: center;
}
    <!DOCTYPE html>
<html>
<head>
<title>Metcalfe's Law Demo</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="code.js"></script>
</head>
<body>
<div id="container">
<div id="demo">
</div>
</div>
</body>
</html>

最佳答案

主要错误非常简单 - 只需将样式 position:relative 更改为 position:absolute:

window.onload = function() {
var num = 12;

var angle = (2 * Math.PI)/(num); var count = 0;
var demo = document.getElementById("demo");
console.log(angle)

function Dot() {
this.angle = angle * count;
count++;
console.log(this.angle,count)
this.x = Math.cos(this.angle) * 200;
this.y = Math.sin(this.angle) * 200;
}

Dot.prototype.create = function() {
var dot = document.createElement("div");
dot.style.top = this.y + 200 + "px";
dot.style.left = this.x + 200 + "px";
dot.className = "dot";
demo.appendChild(dot);
}

for (var i = 0; i < num; i++) {
var d = new Dot();
d.create();
}
}
.dot {
height: 20px;
width: 20px;
border-radius: 50%;
background: blue;
position: absolute;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<title>Metcalfe's Law Demo</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="code.js"></script>
</head>
<body>
<div id="container">
<div id="demo">
</div>
</div>
</body>
</html>

关于javascript - 将点均匀分布在圆上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44358067/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com