如何使用for循环在不同角度绘制圆形线条

时间:2015-07-11 10:06:02

标签: javascript jquery html

我使用下面的代码在圆圈中绘制一条线,现在我想在不同的角度绘制12条线,相同的空间和应该触摸圆圈。

<!DOCTYPE html>
    <html>
    <head>

    <style>

    #straight{
    height: 30px;
    border-right: 1px solid blue; 
    -webkit-transform: rotate(**" for loop value must be displayed"** deg);
    transform: rotate(**" for loop value must be displayed"** deg); 
    position: absolute;
    top:40px;
    left:400px;
    } 
    #circle {
      height: 30px;
      width: 31px;
      margin-left: 81px;
      margin-top: 0px;
      background-color: #fff;
      border: 2px solid blue;
      border-radius: 65px;
      position:absolute;

    }    
    </style>    
    </head>    
    <body>

                        <div>
                                <div id="circle">                       
                                 <div style="position:relative; top:-40px; left:-385px;">
                                    <div id="straight"></div>

                             </div>
                        </div>

    </body>
    </html>

请帮助我&amp;提前谢谢

1 个答案:

答案 0 :(得分:1)

选中fiddle

它使用函数DrawLine(x1,y1,x2,y2)在给定的坐标之间画一条线。

基本上,它创建宽度较小的div并根据斜率旋转它们。

看起来像带轮辐的轮子。

如果需要,这是wheel in action

以下是摘录。

&#13;
&#13;
drawNLines(12, 40, 40, 40);

function drawNLines(N, centreX, centreY, radius) {
  for (i = 0; i < N; i++) {
    angle = 360 / N;
    x2 = centreX + radius * Math.cos(Math.PI * angle * i / 180);
    y2 = centreY + radius * Math.sin(Math.PI * angle * i / 180);
    DrawLine(centreX, centreY, x2, y2);
  }
}


function DrawLine(x1, y1, x2, y2) {

  if (y1 < y2) {
    var pom = y1;
    y1 = y2;
    y2 = pom;
    pom = x1;
    x1 = x2;
    x2 = pom;
  }

  var a = Math.abs(x1 - x2);
  var b = Math.abs(y1 - y2);
  var c;
  var sx = (x1 + x2) / 2;
  var sy = (y1 + y2) / 2;
  var width = Math.sqrt(a * a + b * b);
  var x = sx - width / 2;
  var y = sy;

  a = width / 2;

  c = Math.abs(sx - x);

  b = Math.sqrt(Math.abs(x1 - x) * Math.abs(x1 - x) + Math.abs(y1 - y) * Math.abs(y1 - y));

  var cosb = (b * b - a * a - c * c) / (2 * a * c);
  var rad = Math.acos(cosb);
  var deg = (rad * 180) / Math.PI

  htmlns = "http://www.w3.org/1999/xhtml";
  div = document.createElementNS(htmlns, "div");
  div.setAttribute('style', 'border:1px solid black;width:' + width + 'px;height:0px;-moz-transform:rotate(' + deg + 'deg);-webkit-transform:rotate(' + deg + 'deg);position:absolute;top:' + y + 'px;left:' + x + 'px;');

  document.getElementById("circle").appendChild(div);

}
&#13;
#circle {
  height: 80px;
  width: 80px;
  margin-left: 30px;
  margin-top: 30px;
  background-color: #fff;
  border: 2px solid blue;
  border-radius: 80px;
  position: absolute;
}
&#13;
<div id="circle"></div>
&#13;
&#13;
&#13;

希望这会有所帮助。 :)