问题:
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 qui...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
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>
回答1:
It just appears as if it is fading this quickly because you are not clearing the canvas, you keep overwriting the same transparent image over each other.
All you need to do is remove the // in front of the clearRect function
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<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);
//you already had it here, i only had to remove the "//"
mainctx.clearRect(0, 0, width, height);
mainctx.globalAlpha = 1 - op;
mainctx.drawImage(testctx.canvas, 0, 0);
if (op <= 0.1) setTimeout(function(){ console.log("done"); }, 1);
else requestAnimationFrame(fade);
}
fade();
</script>
</body>
</html>
https://jsbin.com/yulekoxuza/edit?html
Hope it helps ;)