均匀地在圆上分布点

时间:2017-06-04 19:39:21

标签: javascript geometry trigonometry

我需要在一个圆周上均匀分布点,而我的智慧不合时宜。结果不是完全圆形而是精确的,特别是在点数较多的情况下。我对它进行了大力研究,但仍然无法弄清楚我在哪里犯了错误。

  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>

1 个答案:

答案 0 :(得分:2)

主要错误是简单的血腥 - 只需将样式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>