不使用css3的径向渐变的不透明度

时间:2014-07-14 07:53:48

标签: javascript html5 canvas radial-gradients

我有一个径向渐变,我想要为不透明度设置动画以使其透明,然后恢复真正的不透明度......

我搜索了诸如

之类的posibles解决方案
context.globalAlpha

但是所有的径向渐变都是看不见的,我想要一个......

其他可能的解决方案?

1 个答案:

答案 0 :(得分:0)

你走在正确的轨道上!

您可以使用context.globalAlpha更改径向渐变的不透明度:

示例代码和演示:http://jsfiddle.net/m1erickson/Cd79L/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color:white; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    // canvas related variables
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;

    // variables used to draw & animate the ring
    var PI2 = Math.PI * 2;
    var cancelAnimationId;
    var startingX=100;
    var endingX=225;
    var x=startingX;
    var deltaX=1;
    var y=100;
    var radius=50;

    // start the animation loop
    requestAnimationFrame(animate);

    // the animation loop
    function animate() {

        // request another animation loop
        requestAnimationFrame(animate);

        // create the gradient at the current x,y
        var radgrad=ctx.createRadialGradient(x,y,0,x,y,radius);
        radgrad.addColorStop(0.00,"green");
        radgrad.addColorStop(1.00,"white");
        ctx.fillStyle=radgrad;

        // draw the ring at the radius set using the easing functions
        ctx.clearRect(0,0,cw,ch);
        ctx.save();
        ctx.globalAlpha=(x-startingX)/100;
        ctx.beginPath();
        ctx.arc(x,y,radius,0,PI2);
        ctx.closePath();
        ctx.fill();
        ctx.restore();

        x+=deltaX;
        if(x<startingX || x>endingX){deltaX*=-1;x+=deltaX;}
    }


}); // end $(function(){});
</script>
</head>
<body>
    <canvas id="canvas" width=300 height=300></canvas>    </body>
</html>