I'm trying to fade the content of one canvas into another. Starting with the script here I have the following which works but I'm confused as to why the fade happens so quickly - why does globalAlpha seem to have almost completely faded the new image in after only 0.2 of op? Script is below and here on jsbin.
<canvas id="main" width="500" height="300"></canvas>
<canvas id="test" width="500" height="300"></canvas>
<script>
var width = 500, height = 300;
var main = document.getElementById('main');
var mainctx = main.getContext('2d');
//begin path, create a rect the size of the canvas
mainctx.beginPath();
mainctx.rect(0, 0, width, height);
mainctx.fillStyle = "#ff0000";
mainctx.fill();
var test = document.getElementById('test');
var testctx = test.getContext('2d');
//begin path, create a rect the size of the canvas
testctx.beginPath();
testctx.rect(0, 0, width, height);
testctx.fillStyle = "#00ff00";
testctx.fill();
var op = 1;
function fade()
{
op -= 0.001;
console.log(op);
//mainctx.clearRect(0, 0, width, height);
mainctx.globalAlpha = 1 - op;
mainctx.drawImage(testctx.canvas, 0, 0);
if (op <= 0.8) setTimeout(function(){ console.log("done"); }, 1);
else requestAnimationFrame(fade);
}
fade();
</script>