gpt4 book ai didi

javascript - Html5 Canvas 中的淡入淡出

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:34:31 26 4
gpt4 key购买 nike

我有一个带有图像的 Canvas ,我想不断淡入和淡出图像。我已经使用了上面的代码:

<!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>

是否可以在 setIntervals 中插入两个函数?我想在 fadeIn 函数之后触发 fadeOut。怎么可能??

最佳答案

这是一种方法:

var alpha = 0,   /// current alpha value
delta = 0.1; /// delta = speed

然后在主循环中增加当前 alpha 的 alpha。当 alpha 达到 0 或 1 个反向 delta 时。这将创建乒乓淡入淡出:

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
}

关于javascript - Html5 Canvas 中的淡入淡出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19258169/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com