// Global Variables
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var x = 0;
var y = 0;
var R = c.width/2;
var r = 0;
var t = 0;
var p = 0;
// Start Drawing
function startDrawing() {
t = 0;
r = $("#r").val();
p = $("#p").val();
validate();
// Create a random color
var timesRun = 0;
var color = '#' + $("#color").val();
if (color == "#") {
color = '#'+Math.floor(Math.random()*16777215).toString(16);
}
// Initial x and y
x = R + (R-r)*Math.cos(t) + p*Math.cos(((R-r)/r)*t); // add R to set 0,0 in the middle of the canvas
y = R + (R-r)*Math.sin(t) - p*Math.sin(((R-r)/r)*t); // add R to set 0,0 in the middle of the canvas
// Start the Drawing
ctx.beginPath();
ctx.strokeStyle = color;
ctx.moveTo(x,y);
var xStart = x;
var yStart = y;
// Use the timer to create drawing
interval = setInterval(function() {
timesRun += 1;
if(timesRun > 1 && x.toFixed(6) == xStart && y.toFixed(6) == yStart) {
clearInterval(interval);
}
drawSpirograph();
}, 20);
}
// Draw Spirograph
function drawSpirograph() {
t += Math.PI/50;
x = R + (R-r)*Math.cos(t) + p*Math.cos(((R-r)/r)*t); // add R to set 0,0 in the middle of the canvas
y = R + (R-r)*Math.sin(t) - p*Math.sin(((R-r)/r)*t); // add R to set 0,0 in the middle of the canvas
ctx.lineTo(x,y);
ctx.stroke();
}
// Validate Input Fields
function validate() {
if (+r >= +R) {
alert("r must be less than R");
exit;
}
if (+p >= +r) {
alert("p must be less than r");
exit;
}
var regex = /^[0-9a-fA-F]{6}$/;
if (regex.test($(color).val()) == false && $(color).val() != "") {
alert("color must be 6 digit hex number");
exit;
}
}
// Stop Drawing
function stopDrawing() {
clearInterval(interval);
}
// Clear Canvas
function clearCanvas() {
clearInterval(interval);
ctx.clear();
}
CanvasRenderingContext2D.prototype.clear =
CanvasRenderingContext2D.prototype.clear || function...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.