gpt4 book ai didi

javascript - Canvas 中一张图像上的 globalAlpha

转载 作者:行者123 更新时间:2023-12-03 11:43:45 25 4
gpt4 key购买 nike

我想用 html5-canvas 做一些动画。我有背景,背景上有杯子,这个杯子里有硬币,这是透明的。当杯子出现时,我想要淡入淡出效果。我有一个问题,因为当我为杯子提供 globalAlpha 时,其余的得到了相同的结果。我想要动画,我可以为每个元素提供淡入淡出效果。现在我有这个:

<body>
<canvas id="myCanvas" width="1600" height="900"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var background = new Image();
var money1 = new Image();
var money2 = new Image();
var money3 = new Image();
var money4 = new Image();
var money5 = new Image()
var mug = new Image();
var move = 0.01;

background.onload = function() {
context.drawImage(background, 0, 0);
}

mug.onload = function(){

context.globalAlpha = 0;
var i = 0;

var imgFadeInter = setInterval(function(){

context.globalAlpha += 0.01;
var a = context.drawImage(mug, 33, 212)
console.log(a, 'text');
i++;
if(i == 10){
clearInterval(imgFadeInter)
}

}, 10);


};
money1.onload = function() {
context.drawImage(money1, 155, 362);
};

money2.onload = function() {
context.drawImage(money2, 158, 360);
};

money3.onload = function() {
context.drawImage(money3, 151, 358);
};
money4.onload = function() {
context.drawImage(money4, 148, 301);
};

money5.onload = function() {
context.drawImage(money5, 136, 265);
};
background.src = 'background-mag.png';
setTimeout(function(){mug.src = 'mug.png'}, 500);
setTimeout(function(){money1.src = 'money1.png'}, 1000);
setTimeout(function(){money2.src = 'money2.png'}, 2000);
setTimeout(function(){money3.src = 'money3.png'}, 3000);
setTimeout(function(){money4.src = 'money4.png'}, 4000);
setTimeout(function(){money5.src = 'money5.png'}, 5000);
</script>

抱歉我的英语不好,我希望我写的内容是可以理解的..

最佳答案

您可以向图像对象添加自定义属性,因此为每个图像添加您想要的 Alpha:

// start with money1's alpha at a low alpha so you can fade it in
// alpha will be divided by 100 later (using ints prevents rounding problems)
money1.alpha=20;

然后,当您在动画循环中drawImage时,您可以根据添加的属性设置单独的globalAlpha:

if(money1.alpha<=100){

// draw money1 at its current alpha
context.globalAlpha=money1.alpha/100;
context.drawImage(money1, 155, 362);

// be sure to tidy up...reset globalAlpha to its default of 1.00
context.globalAlpha=1.00;

// increase the alpha
money1.alpha+=1;


};

祝您的项目顺利!

关于javascript - Canvas 中一张图像上的 globalAlpha,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26147228/

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