JSFiddle - React, Tailwind, and code Playground
by trochiml
HTML
<button onclick="drawSpirograph();">Draw Spirograph</button>
<canvas id="myCanvas" width="600" height="600" style="border:1px solid #d3d3d3;">
</canvas>
<div>
</div>
JavaScript
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
function drawSpirograph() {
// ctx.clear();
var R = Math.floor(Math.random()*147)+151;
var r= Math.floor(Math.random()*(299-R)/2)+1;
var a = Math.floor(Math.random()*(300-R-2*r))+1;
alert ("R is "+R+" r is "+r+" a is "+a);
var t = 0;
var x=(R+r)*Math.cos(t) - (r+a)*Math.cos(((R+r)/r)*t)+300;
var y=(R+r)*Math.sin(t) - (r+a)*Math.sin(((R+r)/r)*t)+300;
ctx.moveTo(x,y);
var coeff = 4;
//(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)+300;
y =(R+r)*Math.sin(t) - (r+a)*Math.sin(((R+r)/r)*t)+300;
ctx.lineTo(x,y);
ctx.stroke();
}
}
function lcm_two_numbers(x, y) {
var ret = (x * y) /( gcd_two_numbers(x, y));
alert ("lcm is "+ret );
return ret;
}
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;
}