title: Update canvas drawing on click with Javascript
body: <p>I'm trying to increase the radius of a circle drawn in canvas using JavaScript functions. </p>
  
  <p>There were many topics with similar issues but couldn't find an answer that would fix this one, I've tried using built-in methods that were suggested like <code>setInterval</code>, <code>setTimeout</code>, <code>window.requestAnimationFrame</code> and clearing the canvas to redraw the circle with the updated variable.</p>
  
  <p>So far the <code>setInterval</code> method displayed the update but kept the previous iterations in the canvas, the clear method doesn't work.</p>
  
  <p>Here's the example :
  <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>//Define globals
  var radiusIncrement = 5;
  var ballRadius = 20;
  
  //Helper functions
  function increaseRadius() {
    ballRadius += radiusIncrement;
  }
  
  function decreaseRadius() {
    if (ballRadius &gt; 0) {
      ballRadius -= radiusIncrement;
    }
  }
  
  
  //Draw handler
  function draw() {
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    ctx.beginPath();
    ctx.arc(canvas.height/2,canvas.width/2,ballRadius,0,2*Math.PI);
    ctx.stroke();
  }
  
  //Event handler
  setInterval(function() {
    draw();
    ctx.clearRect(0,0,canvas.width,canvas.height);
  }, 100);</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!--Create frame and assign callbacks to event handlers--&gt;
  &lt;button type="button" onclick="increaseRadius()"&gt;Increase Radius&lt;/button&gt;
  &lt;button type="button" onclick="decreaseRadius()"&gt;Decrease Radius&lt;/button&gt;
  &lt;canvas id="myCanvas" width="400" height="400" style="border:1px solid #000000;"&gt;&lt;/canvas&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>Rather than using setInterval, is there a way to streamline the code using and use an event handler to refresh the canvas on every onlick ?</p>
  
  <p>Thanks for your help.</p>
  
  <p>Cheers.</p>