js圆周运动动画_JavaScript动画实例:沿圆周运动的圆圈

1.一个沿圆周运动的圆圈

一个半径为size的圆圈以画布的中心(canvas.width/2,canvas.height/2)为起点,沿着一个圆周运动。编写如下的HTML代码。

沿圆周运动的圆圈

varcanvas=document.createElement('canvas');varctx=canvas.getContext('2d');

document.body.appendChild(canvas);

canvas.width=window.innerWidth;

canvas.height=window.innerHeight;

ctx.beginPath();

ctx.fillStyle= 'rgba(0, 0, 0, 1)';

ctx.fillRect(0,0, canvas.width, canvas.height);varangle=360;varpos=[canvas.width/2,canvas.height/2];varsize= 10;varspeed= 1;varcurve= 0.5;varcolor= 'rgba(69,204,255,.95)';functiondraw ()

{varradians=angle*Math.PI/180;

pos[0]+=Math.cos(radians)*speed;

pos[1]+=Math.sin(radians)*speed;

angle+=curve;

ctx.strokeStyle=color;

ctx.beginPath();

ctx.arc(pos[0],pos[1],size,0,2*Math.PI);

ctx.stroke();

window.requestAnimationFrame(draw);

}

window.requestAnimationFrame(draw);

View Code

在浏览器中打开包含这段HTML代码的html文件,可以在浏览器窗口中呈现出如图1所示的动画效果。

图1  沿圆周运动的一个圆圈

由图1可知,圆圈运动的起点(canvas.width/2,canvas.height/2)位于运动所沿的圆周上angle==360°的位置。

2.两个沿圆周运动的圆圈

在画布中放置两个圆圈,两个圆圈的起点均位于画布中心(canvas.width/2,canvas.height/2),一个圆圈从所沿圆周的45°处沿圆周运动,另一个圆圈从所沿圆周的135°处沿圆周运动。编写如下的HTML代码。

沿圆周运动的圆圈

varcanvas=document.createElement('canvas');varctx=canvas.getContext('2d');

document.body.appendChild(canvas);

canvas.width=window.innerWidth;

canvas.height=window.innerHeight;

ctx.beginPath();

ctx.fillStyle= 'rgba(0, 0, 0, 1)';

ctx.fillRect(0,0, canvas.width, canvas.height);varangle1=45;varangle2=135;varpos1=[canvas.width/2,canvas.height/2];varpos2=[canvas.width/2,canvas.height/2];varsize= 10;varspeed= 1;varcurve= 0.5;varcolor1= 'rgba(69,204,255,.95)';varcolor2= 'rgba(255,212,50,.95)';functiondraw ()

{varradians=angle1*Math.PI/180;

pos1[0]+=Math.cos(radians)*speed;

pos1[1]+=Math.sin(radians)*speed;

angle1+=curve;

radians=angle2*Math.PI/180;

pos2[0]+=Math.cos(radians)*speed;

pos2[1]+

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值