javascript 在 Html5 画布中淡入淡出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19258169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
FadeIn FadeOut in Html5 canvas
提问by Jose Ramon
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??
是否可以在 setIntervals 中插入两个函数?我想在fadeIn 函数之后触发fadeOut。这怎么可能??
回答by
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:
在主循环中,然后用当前的 alpha 增加 alpha。当 alpha 达到枯萎 0 或 1 反向增量时。这将创建乒乓淡入淡出:
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
}