title: cancel canvas animation by adding eventListener
body: <p>I am trying to reset my rectangle animation from the starting point when I resize the browser, the code is like this:</p>
  
  <pre><code>/*from basic setup*/
  canvas = document.getElementById("myCanvas");
  canvas.height = window.innerHeight;
  canvas.width = window.innerWidth;
  ctx = canvas.getContext("2d");
  
  /*the "resize" event and the reset function should be triggered */
  window.addEventListener("resize",function(){
       canvas.height = window.innerHeight;
       canvas.width = window.innerWidth;
       //cancelAnimationFrame(timeID)
       //theRect();
  });
  
  /*drawing the rectangle*/
  var x = 0,y = canvas.height - 100,w = 100, h = 100,dx=1;
  
  function theRect(){
   ctx.fillStyle = "lightblue";
   ctx.fillRect(x,y,w,h)
   x+=dx;
   if(x+w&gt;canvas.width/2 || x&lt;0){
      dx=-dx;
   }
  }
  
  /*start animation*/
  
  function animate(){
      ctx.clearRect(0,0,canvas.width,canvas.height);
      theRect();
      requestAnimationFrame(animate);
  
  }
  //var timeID = requestAnimationFrame(animate)
  
  animate();
  </code></pre>
  
  <p>I was thinking if each time the browser resized, the rectangle has to be reset to the starting point as<code>ctx.fillRect(0,canvas.height-100,100,100)</code>and continue its animation.</p>
  
  <p>So my original approach to solve this is using <code>cancelAnimationFrame()</code>this method to kill the animation first and calling this function again within my <code>eventlistener</code> so each time the event was fired, the animation will stop and run again.</p>
  
  <p>but <code>cancellAnimationFrame()</code>function requires the target animation timeID, and there is no way to track this timeID inside my <code>animate()</code>function since if I am calling <code>var timeID = requestionAnimationFrame(animate)</code>it will come to huge lag spikes on my browser</p>
  
  <p>just the more I want to modify to more I become to loss with this, so my questions are: </p>
  
  <p>1, is this wise to use <code>cancelAnimationFrame</code> here as the first step to reset my animation? </p>
  
  <p>2, is there any other good way to achieve this "reset" purpose? </p>
  
  <p>Could someone please help me with this? thanks in advance.</p>