user2478478
user2478478

Reputation: 1

circle moving in a round path

How can i move a circle in a round path using HTML5 and javascript My code to move circle in a linear path is given below. how can i change the path to a circular one?

 <script>

   var context;
   var x=100;
   var y=250;
   var dx=5;
   var dy=5;

    function move()
    {
     context= rectangle.getContext('2d');
     setInterval(draw,20);
    }

   function draw()
   {
    context.clearRect(0,0,400,400);
    context.beginPath();
    context.fillStyle="#0000ff";

    context.arc(x,y,20,0,Math.PI*2,true);
    context.closePath();
    context.fill();

    x+=dx;


   }
  </script>

    <canvas id="rectangle" width="400" height="400" style="border:1px solid #000000;" >
    </canvas>
    <input type="button" onClick="move();" width="100" height="100" value="click "/>

</body>

Upvotes: 0

Views: 1206

Answers (1)

sumitb.mdi
sumitb.mdi

Reputation: 990

You have already done everything; now in order to move it in circle instead of on a line you need to choose a dƟ instead of dx, so that you can move both x and y coordinates.

Now lets say you have your center at (a,b) and radius of the path as r then your path will look as follows:

enter image description here

so there you have your coordinates rcosƟ, rsinƟ

so in your draw function do this

x=a+r*cos(Ɵ);
y=b+r*sin(Ɵ);
Ɵ+=dƟ;

instead of

x+=dx;

Choose dƟ in radian precisely so that the movement look smooth. [also choose some viable variable names instead of Ɵ and dƟ]

Upvotes: 1

Related Questions