title: create animation while user is hovering over canvas
body: <p>I am trying to add images and animate them when a user is hovering on the canvas, and once they move the mouse off the canvas I want to stop new images appearing. </p>
  
  <p>To achieve this I have tried to set an interval on the new image to trigger every 100ms and then if the user moves the mouse off the canvas this function should stop triggering.  </p>
  
  <pre><code>canvas.addEventListener("mouseover", setInterval(newImage, 100), false);
  canvas.addEventListener("mouseout", clearInterval(newImage), false);
  </code></pre>
  
  <p><strong>JS CODE BELOW</strong></p>
  
  <p><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>  //gets canvas element
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
  
    function newImage() {
  
      //random position on the canvas
      var randomPosition = parseInt(Math.random() * window.innerWidth);
  
      var images = [
        'http://www.convoy.me/image/landing/Scratcher.png',
        'http://www.convoy.me/image/landing/push_harder_0006.png'
      ];
  
      var y = window.innerHeight;
  
      //selects a random image
      var randomImage = parseInt(Math.random() * images.length);
  
      //IIFE draw
      (function draw() {
        var imageObj = new Image();
        imageObj.onload = function() {
  
          ctx.clearRect(randomPosition - imageObj.width, y, imageObj.width, imageObj.height);
  
          y -= 10;
  
          ctx.drawImage(imageObj, randomPosition - imageObj.width, y, imageObj.width, imageObj.height);
  
          if (y &gt; -imageObj.height) {
            requestAnimationFrame(draw)
          }
        };
        imageObj.src = images[randomImage];
      })();
    }
  
    canvas.addEventListener("mouseover", setInterval(newImage, 100), false);
    canvas.addEventListener("mouseout", clearInterval(newImage), false);</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;canvas id="canvas"&gt;&lt;/canvas&gt;</code></pre>
  </div>
  </div>
  </p>