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



我有一个不断增长的圆的代码,但我试图在画布/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();和其他变体,但没有运气。 提前谢谢你!

尝试以下动画代码。

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

相关内容

最新更新