Orbiting - Object following a circle JavaScript
Move and animate a satellite object circling a larger object (not simulating physics)
by Luke Nickerson
HTML
<div class="space">
<div class="planet"></div>
<div class="orbit"></div>
<div class="sat" id="sat1"></div>
</div>
<p>
Based on <a href="http://stackoverflow.com/a/10349614/1766230">this SO answer</a>.
</p>
CSS
.space {
position: relative;
width: 200px;
height: 200px;
margin: 3em;
}
.space > div {
position: absolute;
border-radius: 100%;
}
.planet {
top: 50px; right: 50px;
width: 100px;
height: 100px;
background-color: #ccc;
/* box-shadow: inset -30px -30px 30px rgba(0,0,0,0.25); */
}
.orbit {
top: 0px; right: 0px;
width: 200px; height: 200px;
border: solid 1px #ccc;
}
.sat {
width: 30px; height: 30px;
background-color: #ccc;
/* box-shadow: inset -10px -10px 10px rgba(0,0,0,0.25); */
}
JavaScript
// init part, set your own values
var sat = {
elt: null
,a: 0 // in radian
,r: 100 // radius
,da: 0.05 // in radian
,x: 0
,y: 0
// Center is actualy center (100, 100) minus
// half the size of the orbiting object 15x15
,center: { x: (100 - 15), y: (100 - 15) }
}
sat.move = function(){
// each modification
this.a += this.da
this.x = this.center.x + (this.r * Math.sin(this.a));
this.y = this.center.y + (this.r * Math.cos(this.a));
//console.log(this.x, this.y);
this.elt.style.top = this.y + "px";
this.elt.style.left = this.x + "px";
}
sat.elt = document.getElementById('sat1');
var loopTimer = setInterval(function(){
sat.move();
}, 50);