如何在函数内的javascript上做一个慢脉冲循环?

时间:2014-08-13 14:01:46

标签: javascript animation canvas geometry

我在javascript中绘制了一些圆形函数,并希望为它添加慢速脉冲效果的功能。以下是我的js代码,有人可以帮我吗?

感谢!!!

Karen x

   function newCircle1 (x,y){

            var ctx=canvas.getContext("2d");

            ctx.fillStyle="rgb(255,255,255,0.65)";
            ctx.beginPath();
            ctx.arc(x,y,10,0,2*Math.PI);
            ctx.fill();         
    }

            function newCircle2 (x,y){

            var ctx=canvas.getContext("2d");

            ctx.fillStyle="rgb(255,255,255)";
            ctx.beginPath();
            ctx.arc(x,y,5,0,2*Math.PI);
            ctx.fill();
        }


        function getMousePos(canvas,evt){

        var rect = canvas.getBoundingClientRect();
        return{

            x: evt.clientX - rect.left,
            y: evt.clientY - rect.top
        };
    }

        canvas.addEventListener('mousemove', function(evt){
            var mousePos = getMousePos (canvas,evt);

            newCircle1(mousePos.x, mousePos.y);
            newCircle2(mousePos.x, mousePos.y);     

        }, false);
}

1 个答案:

答案 0 :(得分:0)

我的例子是基于markE的例子。这具有在两个最小点和最大点之间振荡的半径和不透明度。调整设置以使绘图输出变得混乱:

<强> JSFiddle Demo

var canvas = document.createElement( 'canvas' ),
    ctx = canvas.getContext( '2d' ),
    width = canvas.width = 300,
    height = canvas.height = 300,
    baseRadius = { min: 3, max: 18 },
    baseOpacity = { min: 0.3, max: 0.7 },
    mouse = { x: -9999, y: -9999 },
    tick = 0,
    osc1,
    osc2,
    bounds;

function onresize() {
  bounds = canvas.getBoundingClientRect();
}

function onmousemove( e ) {
  mouse.x = e.pageX - bounds.left;
  mouse.y = e.pageY - bounds.top;    
}

function loop() {
  requestAnimationFrame( loop );
  osc1 = 0.5 + Math.sin( tick / 13 ) * 0.5;
  osc2 = 0.5 + Math.sin( tick / 19 ) * 0.5;

  var radius = baseRadius.min + ( ( baseRadius.max - baseRadius.min ) * osc1 ),
      opacity = baseOpacity.min + ( ( baseOpacity.max - baseOpacity.min ) * osc1 );

  ctx.beginPath();
  ctx.arc( mouse.x, mouse.y, radius, 0, Math.PI * 2 );
  ctx.fillStyle = 'rgba(255, 255, 255, ' + opacity + ')';
  ctx.fill();

  tick++;
}

window.addEventListener( 'resize', onresize );
window.addEventListener( 'mousemove', onmousemove );

document.body.appendChild( canvas );
onresize();
loop();

GIF Animation