title: HTML keydown delete old canvas
body: <p>The code below should make a canvas appear when I click on "space". Every time I click on "space" then it should delete the old canvas and draw a new one (the position is chosen among 6 different possibilities at each click). </p>
  
  <p>I have a problem with the code because it does not delete the old canvas and keeps on drawing them one on top of the other.
  How can I fix the problem?</p>
  
  <pre><code>&lt;html&gt;
    &lt;head&gt;
    &lt;/head&gt;
  
    &lt;link rel="stylesheet" href="cssFiles/blackBackground.css"&gt;
  
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"&gt;&lt;/script&gt;
  
    &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"&gt;&lt;/script&gt;
  
    &lt;canvas id="myCanvas" width="1260" height="1000" style="border:1px solid red;"&gt;&lt;/canvas&gt;
  
      &lt;script&gt;
  
      var circle = [[-350,-300],[-350,0],[-350,300],[350,-300],[350,0],[350,300]];
      $(document).ready(function() {
  
          document.addEventListener("keydown", function (e) {
  
  
               if  (e.keyCode === 32) { // space is pressed
  
                  var idx_circle = Math.floor(Math.random() * 6) 
                  drawCircle(circle[idx_circle][0],circle[idx_circle][1],2.5,1);
                }    
  
          });
        })
  
       function drawCircle(centerX,centerY, scaleX, scaleY){
  
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    var radius = 120;
  
    // save state
   context.save();
  
    // translate context
    context.translate(canvas.width/2 , canvas.height/2 );
  
    // draw circle which will be stretched into an oval
    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  
    // restore to original state
    context.restore();
  
    // apply styling
    context.fillStyle = 'white';
    context.fill();
    context.lineWidth = 20;
    context.strokeStyle = 'white';
    context.stroke();
  }
  
  
      &lt;/script&gt;
  
  
    &lt;/body&gt;
  &lt;/html&gt;      
  </code></pre>