如何制作一个for循环,在它完成之前重新启动圆形动画,使它看起来像一个脉动的圆圈

问题描述 投票:0回答:1

我有一个不断增长的圈子的代码,但我试图让几个圈子在canvas / javascript中增长。我想让它看起来像它的脉冲,不断地抽出圆圈,就像声波一样。我对编码很新,所以我不确定语法,但是这里的if(radius of circle> width of canvas/30px){create new circle}行是我到目前为止的代码

window.onload=function(){
    function animate() {
        var c=document.getElementById("myCanvas");
        var ctx= c.getContext("2d");
        ctx.clearRect(0, 0, c.width, c.height);

        if(i > 200) {
            i = 1;
        }

        if( i > 40) {
            ctx.beginPath();
            ctx.arc(c.width/2, c.width/2, i-40, 0, 2 * Math.PI, true);
            ctx.lineWidth = 7;
            ctx.stroke();
        }
        i++;
        setTimeout(animate, 10);
    }
    var i = 0;
    animate();
  }
}

我试过放入if(i>30px)animate();和其他变种,但没有运气。先感谢您 !

javascript for-loop canvas jquery-animate geometry
1个回答
1
投票

尝试下面的动画代码。

<html>
<body>
<script>
window.onload=function(){
    function animate() {
        var c=document.getElementById("myCanvas");
        var ctx= c.getContext("2d");
        ctx.clearRect(0, 0, c.width, c.height);

        if(i > 300) {	// adjust the place need to stop the animation at canvas, how many pixels that the stop point close to the origin
            i = 1;	
        }

        if( i > 1) {
	    var j = 0;
	    while(j<50){	// number of circles in the wave (50/5)
		    ctx.beginPath();
		    ctx.arc(c.width/2, c.height+300, i+(j*5), 0, 2 * Math.PI, true);	// i=(j*5) adjust the distance between circles
		    ctx.lineWidth = 7;
		    ctx.stroke();
	            j += 5;
	    }
        }
        i++;
        setTimeout(animate, 10);
    }
    var i = 0;
    animate();
}
</script>
<canvas id="myCanvas" width="400" height="200"></canvas>
</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.