Simple orbital movement on Canvas

In this tutorial you can learn how to create simple orbital movement using HTML Canvas and JavaScript. 

This is very basic step-by-step guide, so everyone can understand it without any previous experience with programming. 

Create new folder anywhere on your computer where you will place your files. You can create this folder on Desktop also. Rename it as "Orbit example". Inside "Orbit example" folder create new text file and rename it as "index.html". 

Open this file with your favorite text editing program and paste code which follows. 

<canvas id="myCanvas" width="500" height="500"></canvas>  
<script src="orbit.js"></script>  

This is main HTML file and as you can see after closing body tag we linked to orbit.js JavaScript file. This file is next for you to create and place inside same "Orbit example" folder.

Here is the code:

 // canvas size is 500x500  
 var c = document.getElementById("myCanvas");  
 var ctx = c.getContext("2d");  
 // Object orbit settings  
 // alpha is starting angle   
 var alpha = 0;  
 // center of rotation position  
 var center = 250;  
 // rotation speed  
 var freq = 1/200;  
 // distance from rotation center  
 var radius = 100;  
   ctx.clearRect(0,0,500,500); // clear canvas  
   //Draw orbit path  
   // draw object  
   alpha += freq;  
   if(alpha >= 2*Math.PI)  
     alpha = 0;  
   var objectX = center + (radius * Math.cos(alpha));  
   var objectY = center + (radius * Math.sin(alpha));  
 }, 10);  
 // drawing function  
 function drawCircle(objectX,objectY,radius,color) {  
   ctx.fillStyle = color;  

First we set some object orbit settings like alpha angle, center, frequency and radius. 

Function setInterval will redraw Canvas every 10 milliseconds. It will draw orbit path every time and after calculation new object position it will draw it on Canvas, which will make animation. 

Function drawCircle is outside of setInterval so we can reuse it later. 

This is result image.

You can, for example double orbiting speed with var freq = 1/100; Experiment with other settings.

Next time I will show you how to attach a satellite to this orbiting object.


Post a Comment