JSFiddle - React, Tailwind, and code Playground

by Tori Hoelscher

HTML

<button onclick="drawSpirographplease();">Please Draw Spirograph</button>
<canvas id="myCanvas" width="800" height="800" style="border:1px solid #d3d3d3;">
</canvas>

JavaScript

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

function drawSpirographplease() {

// ctx.clear();
    
var R = Math.floor(Math.random()*320)+100;
var r= Math.floor(Math.random()*(499-R)/2)+1;
var a = Math.floor(Math.random()*(400-R-2*r))+1;
alert ("The large R is "+R+", the small r is "+r+" and the a is "+a); 
var t = 0;
var x=(R+r)*Math.cos(t) - (r+a)*Math.cos(((R+r)/r)*t)+400;
var y=(R+r)*Math.sin(t) - (r+a)*Math.sin(((R+r)/r)*t)+400;

ctx.moveTo(x,y);
 
var coeff = 7;
 //i use this equation for the spirograph:: (lcm_two_numbers(2*r+a, R))/(2*r+a);

for ( t = 0; t <= coeff*Math.PI; t+=0.01) {

  x = (R+r)*Math.cos(t) - (r+a)*Math.cos(((R+r)/r)*t)+400;
	y =(R+r)*Math.sin(t) - (r+a)*Math.sin(((R+r)/r)*t)+400;
  ctx.lineTo(x,y);
  ctx.stroke();
 }
}
//changing the the numbers in the equation is fun
function lcm_two_numbers(x, y) {
 var ret = (x * y) /( gcd_two_numbers(x, y));
 alert ("lcm is "+ret );
 return  ret;
}
//alert is to tel me what the lcm is
function gcd_two_numbers(x, y) {
 x = Math.abs(x);
 y = Math.abs(y);
 while(y) {
  var t = y;
  y = x % y;
  x = t;
 }
 return x;
 }