螺旋动画JavaScript

时间:2014-10-05 17:03:57

标签: javascript animation

我正在学习JavaScript,我发现了以下文章:http://www.html5code.nl/tutorial-canvas-animation-spiral-movement/

你能告诉我函数spiralMotion1()是如何工作的吗? 我想自定义速度和距离。

编辑:将其细分为具体细节:为什么要使用cos。和罪。为什么要使用rotationRadius? setAngle函数如何影响结果?度数变量在哪里发挥作用?

代码:

function spiralMotion1(){
  var degrees = 0;
  var Angle;
  var rotationRadius=2;
  var rotationRadiusIncrease = 1;
  var ballRadius=20
  var centerX;
  var centerY;
  var x;
  var y;
  var animate=true;
  var breadcrumbs = new Array();
  var crumbRadius=1;
  var canvas = jQuery("#spiral_motion1");
  var context = canvas.get(0).getContext("2d");
  //function Ball(x,y,radius,color,strokeColor,lineWidth) in ball.js
  var ball_3 = new Ball(-10,-10,20,'#f00','#000',7);
  var parentWidth=jQuery(canvas).parent().width();
  var canvasWidth=context.canvas.width = parentWidth;
  var canvasHeight=context.canvas.height= 288;

  if (!checkForCanvasSupport) {
  return;
  }

  (function drawFrame() {
  window.requestAnimationFrame(drawFrame, canvas);


  if(animate){
  context.clearRect(0,0,canvasWidth,canvasHeight); // clear canvas
  //Make the Canvas element responsive for desktop, tablet and smartphone.
  centerX = canvasWidth/2;
  centerY = canvasHeight/2
  Angle = degrees * (Math.PI / 180);
  degrees = degrees + 1;
  ball_3.x=rotationRadius * Math.cos(setAngle()) + centerX;
  ball_3.y=rotationRadius * Math.sin(setAngle()) + centerY;
  ball_3.draw(context);

  //add a breadcrumb to the breadcrumbs array
  breadcrumbs.push({x:ball_3.x,y:ball_3.y});
  //draw the breadcrumbs that shows the track of the movement
  context.globalCompositeOperation = "destination-over";
  showBreadcrumbs(breadcrumbs);

  rotationRadius += rotationRadiusIncrease/5
  if ((ball_3.y + ballRadius+4) > canvas.height()){
  animate=false;
  }
  }
  }());//end drawFrame
 function setAngle(){
  Angle = degrees * (Math.PI / 180);
  degrees = degrees + 2;
  return Angle;
  }//end setAngl()

  function showBreadcrumbs(breadcrumbs){
  for (var i = 0; i< breadcrumbs.length; i++) {
  context.beginPath();
  context.arc(breadcrumbs[i].x,breadcrumbs[i].y,crumbRadius,0, 2*Math.PI,false);
  context.closePath();
  context.fillStyle="#999";
  context.fill();
  }
  }//end showBreadcrumbs()
}//end spiralMotion1()

1 个答案:

答案 0 :(得分:1)

归结为基本几何。如果你想到一个在2D中绕一个点运行的物体,它的运动可以用半径(距离轨道点的距离)和一个时间函数的角度来表征。如果您知道半径和角度,那么您可以使用cos和sin函数计算身体位置。

Circular motion geometry

通过随时间改变半径,您将获得螺旋而不是简单的圆圈。