title: How does the JavaScript Canvas globalAlpha Property work?
body: <p>I'm trying to make a fade out effect with JavaScript on the Canvas element. I'm currently have two sollutions for this. In theory, both should work fine, but in practice, only one does, and I wonder why.</p>
  
  <p><strong>The not working code is the following:</strong></p>
  
  <pre><code>var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  var i = 1;
  requestAnimationFrame(test);
  
  function test(){
   i-=0.01;
   ctx.fillStyle = "white";
   ctx.fillRect(20, 20, 75, 50);
   ctx.globalAlpha = i;
   ctx.fillStyle = "red";
   ctx.fillRect(20, 20, 75, 50);
   requestAnimationFrame(test);
  }
  </code></pre>
  
  <p>What I wanted to achieve, is to gradually change the alpha value of the current context, in order to fade it to white. After a while, it should have full transparency, but it does not. It stops right before reaching that state. Here it is in JSFiddle: <a href="https://jsfiddle.net/bq75v1mm/" rel="nofollow">https://jsfiddle.net/bq75v1mm/</a></p>
  
  <p><strong>The working code is the following:</strong></p>
  
  <pre><code>var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  var i = 1;
  requestAnimationFrame(test);
  function test(){
   i-=0.01;
   ctx.fillStyle = "white";
   ctx.fillRect(20, 20, 75, 50);
   ctx.fillStyle = "rgba("+255+","+0+","+0+","+i+")";
   ctx.fillRect(20, 20, 75, 50);
   requestAnimationFrame(test);
  }
  </code></pre>
  
  <p>With this code, I'm just simply changing the alpha value of the given fillStyle for the upcoming rectangle, and it works like a charm, and makes the square vanish into thin air. Here it is in JSFiddle: <a href="https://jsfiddle.net/mxtynwwd/" rel="nofollow">https://jsfiddle.net/mxtynwwd/</a></p>
  
  <p>I would like to understand why doesn't the first sollution work? Why can't I lower the globalAlpha value after a given minimum? Or is the problem in the code?</p>