Madison
Madison

Reputation: 31

How to rotate a semi-circle made of points with javascript/jquery

More of a math questions than javascript... I have this code to create a semi-circle out of smaller circles but I am not sure how to rotate it so that the semi circle starts at the top of the circle and not the side (rotate it 45º to the left).

var items = 9;

for (var i = 0; i < items; i++) {

  var x = 200 + 50 * Math.cos(1.1 * Math.PI * i / items);
  var y = 100 + 50 * Math.sin(1.1 * Math.PI * i / items);

  $("body").append("<div class='point' style='left:" + x + "px;top:" + y + "px'></div>");

}
.point {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: white;
  border: 1px solid black;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Current Output, Desired Output

Thanks!

Upvotes: 3

Views: 653

Answers (3)

trincot
trincot

Reputation: 350272

You can swap the sin and cos calls. Not related to your question, but maybe you like the more jQuery style of adding elements:

var items = 9;
for (var i = 0; i < items; i++) {
  var x = 200 + 50 * Math.sin(1.1 * Math.PI * i / items);
  var y = 100 + 50 * Math.cos(1.1 * Math.PI * i / items);
  $("body").append($("<div>").addClass("point").css({left: x, top: y}));
}
.point {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: white;
  border: 1px solid black;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

baeyun
baeyun

Reputation: 228

I believe this is what you want:

var items = 8;

for(var i = 0; i < items; i++) {

    var x = 200 + 50 * Math.cos(Math.PI * i / items);
    var y = 100 + 50 * Math.sin(Math.PI * i / items); 
    
    $("#center").append("<div class='point' style='left:"+ x +"px;top:"+ y +"px'></div>");

}
#location {
  
    width:200px;
    height:200px;
    /* border-radius:100px; */
    background: black;
    position:relative;
    left:200px;
    top:100px;
    
}

#center {
  transform: rotateZ(-80deg);
}

.point {
  
    width:8px;
    height:8px;
    border-radius:50%;
    background: white;
    border: 1px solid black;
    position:absolute;
    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="center"></div>

Upvotes: 3

Temani Afif
Temani Afif

Reputation: 272909

Simply invert x/y values in the top/left:

var items = 9;
for (var i = 0; i < items; i++) {

  var x = 100 + 50 * Math.cos(1.1 * Math.PI * i / items);
  var y = 200 + 50 * Math.sin(1.1 * Math.PI * i / items);

  $("body").append("<div class='point' style='left:" + y + "px;top:" + x + "px'></div>");

}
.point {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: white;
  border: 1px solid black;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions