Reputation: 5444
I ve got an canvas with an image and i want to fadein and fade out the image constantly. I ve used the above code:
<!DOCTYPE HTML>
<html>
<head>
<script>
var canvas;
var context;
var ga = 0.0;
var timerId = 0;
var timerId1 = 0;
function init()
{
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");
timerId = setInterval("fadeIn()", 300);
console.log(timerId);
}
function fadeIn()
{
context.clearRect(0,0, canvas.width,canvas.height);
context.globalAlpha = ga;
var photo = new Image();
photo .onload = function()
{
context.drawImage(photo , 0, 0, 450, 500);
};
photo .src = "photo .jpg";
ga = ga + 0.1;
if (ga > 1.0)
{
fadeOut();
goingUp = false;
clearInterval(timerId);
}
}
function fadeOut()
{
context.clearRect(0,0, canvas.width,canvas.height);
context.globalAlpha = ga;
var photo = new Image();
photo .onload = function()
{
context.drawImage(photo , 0, 0, 450, 500);
};
photo .src = "photo .jpg";
ga = ga - 0.1;
if (ga < 0)
{
goingUp = false;
clearInterval(timerId);
}
}
</script>
</head>
<body onload="init()">
<canvas height="500" width="500" id="myCanvas"></canvas>
</body>
Is it possible to insert two functions into setIntervals?? I want to trigger fadeOut after fadeIn function. How is it possible??
Upvotes: 2
Views: 25070
Reputation:
Here is one way of doing this:
var alpha = 0, /// current alpha value
delta = 0.1; /// delta = speed
In the main loop then increase alpha with current alpha. When alpha has reached wither 0 or 1 reverse delta. This will create the ping-pong fade:
function loop() {
alpha += delta;
if (alpha <= 0 || alpha >= 1) delta = -delta;
/// clear canvas, set alpha and re-draw image
ctx.clearRect(0, 0, demo.width, demo.height);
ctx.globalAlpha = alpha;
ctx.drawImage(img, 0, 0);
requestAnimationFrame(loop); // or use setTimeout(loop, 16) in older browsers
}
Upvotes: 7