28 February 2018

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. 


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

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;  
 setInterval(function(){   
   ctx.clearRect(0,0,500,500); // clear canvas  
   //Draw orbit path  
   ctx.beginPath();  
   ctx.arc(center,center,100,0,2*Math.PI);  
   ctx.stroke();  
   ctx.closePath();  
   // 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));  
   drawCircle(objectX,objectY,20,"blue");  
 }, 10);  
 // drawing function  
 function drawCircle(objectX,objectY,radius,color) {  
   ctx.beginPath();  
   ctx.arc(objectX,objectY,radius,0,2*Math.PI);  
   ctx.fillStyle = color;  
   ctx.fill();  
   ctx.stroke();   
   ctx.closePath();  
 }  

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.

o_O

0 comments:

 

template by blogger templates