globalAlpha在画布上的一个图像上

时间:2014-10-01 17:36:09

标签: javascript html5-canvas alpha-transparency

我想用html5-canvas做一点动画。我有背景,杯子在背景,硬币在这个杯子是透明的。当杯子出现时我想要淡化效果。我有一个问题,因为当我给globalball提供mug时,剩下的就得到了相同的结果。我想要动画,我可以为每个元素提供淡入淡出效果。现在我有了这个:

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

对不起我的英语,我希望我写的是可以理解的..

1 个答案:

答案 0 :(得分:1)

您可以为图像对象添加自定义属性,因此请为每个图像添加所需的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;


};    

祝你的项目好运!