Spirograph Canvas

by wooozy

HTML

<button onclick="doDrawing();">Start Drawing</button>
<button onclick="stopDrawing();">Stop Drawing</button>
<canvas id="myCanvas" width="500" height="500">
Your browser does not support the HTML5 canvas tag.</canvas>

CSS

body{
background-color:#000;
}

JavaScript

var t = 0;
var r= 15;
var p = 0;
var c = document.getElementById("myCanvas");
var R = c.width/2;
var ctx = c.getContext("2d");




function doDrawing() {
    t = 0;
    p =30;
    
    
    
    

     
    // Clear the Canvas
    ctx.clear();
    
    // Create a random color
    var timesRun = 0;
    var color =  '#'+Math.floor(Math.random()*16777215).toString(16);
    
    // Initial x and y
    var x = R+t*Math.cos(0);
    var y = R+t*Math.sin(0);
    
    

    // Start the Drawing
    ctx.beginPath();
    ctx.strokeStyle = color;
    ctx.moveTo(x,y);
      
    //Use the timer to create drawing
    var interval = setInterval(function(){
    timesRun += 1;
    if(timesRun === 100){
        clearInterval(interval); }
        
    drawSpirograph();}, 20); 
    
}
function drawSpirograph()
{
  t += 5; 
  x = Math.floor(R+t*Math.cos(t));
  y = Math.floor(R+t*Math.sin(t));

  ctx.lineTo(x,y);  
  ctx.stroke();
   
}


CanvasRenderingContext2D.prototype.clear = 
  CanvasRenderingContext2D.prototype.clear || function (preserveTransform) {
    if (preserveTransform) {
      this.save();
      this.setTransform(1, 0, 0, 1, 0, 0);
    }

    this.clearRect(0, 0, this.canvas.width, this.canvas.height);

    if (preserveTransform) {
      this.restore();
    }           
};