温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript怎么实现圆周运动动画

发布时间:2022-03-02 10:56:38 来源:亿速云 阅读:321 作者:iii 栏目:web开发

今天小编给大家分享一下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]+=Math.sin(radians)*speed;

  angle2+=curve;

  ctx.strokeStyle=color1;

  ctx.beginPath();

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

  ctx.stroke();

  ctx.strokeStyle=color2;

  ctx.beginPath();

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

  ctx.stroke();//fade();

  window.requestAnimationFrame(draw);

  }functionfade ()

  {

  ctx.beginPath();

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

  ctx.fillRect(0,0, canvas.width, canvas.height);

  }

  window.requestAnimationFrame(draw);

  View Code

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

以上就是“JavaScript怎么实现圆周运动动画”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI