我想用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 - globalAlpha在 Canvas 中的一张图像上,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26147228/