A spinning circle on a spinning circle

< html > < body > < canvas id =" myCanvas " width =" 800 " height =" 600 "></ canvas > < script > function animate () { let tau = counter / ( Math . PI * 15 . 5 ); let tau2 = counter / Math . PI ; let x1 = Math . sin ( tau ) * r1 + 200 ; let y1 = Math . cos ( tau ) * r1 + 200 ; let x2 = x1 + Math . sin (tau2) * r2; let y2 = y1 + Math . cos (tau2) * r2; context . fillRect (x2, y2, 2 , 2 ); counter ++; window . requestAnimationFrame ( animate ); } let canvas = document . getElementById (' myCanvas '); let context = canvas . getContext ('2d'); let counter = 0 ; let r1 = 100 ; let r2 = 15 ; animate (); </ script > </ body > </ html >

Remember those plastic toys where you put a pencil in a small hole in a circle and spin it inside a larger circle to draw geometric shapes? Let's build something similar in JavaScript!Such shapes are called hypotrochoids in geometry, but who cares. Let's begin our coding exercise with a simple version:Here's how it works:[1-4] HTML setup[6-16] the main animation loop:[7-8] calculate the angles of the small and the big circle. We'll make big one spin 15.5 times slower than the small one.[9-10] calculate the point on the big circle - this will be the center of the small circle[11-12] calculate the point on the small circle - this point will actually be drawn on the canvas[13] draw the point on the small circle[14] increase the counter[15] request the next animation frameNow we just need to kick it off:[18-19] canvas setup[20] initialize the counter[21-22] arbitrary values for the small (r1) and big (r2) circle radiuses[23] start the animation!Now that you get the idea, let's make it easier to change the radiuses and the angular velocities of the circles.Here's what it will look like. On mobile devices it looks best in a new window (click here).