JavaScript Animations, Part I: A Circle Animation - Doc JavaScript | WebReference

JavaScript Animations, Part I: A Circle Animation - Doc JavaScript


A Circle Animation

The only difference between sliding an element and moving it in a circular path is the math. Therefore, the last segment of our circle() method is identical to that of the slideBy() method. Let's take a look at the circle() method:

function circle(radius, angle0, angle1, steps, -->
interval, statement) {
  var dangle = angle1 - angle0;
  var sangle = dangle / steps;
  var x = this.left();
  var y = this.top();
  var cx = x - radius * Math.cos(angle0 * Math.PI / 180);
  var cy = y + radius * Math.sin(angle0 * Math.PI / 180);
  var ar = new Array();
  for (var i = 0; i < steps; i++) {
    angle0 += sangle;
    x = cx + radius * Math.cos(angle0 * Math.PI / 180);
    y = cy - radius * Math.sin(angle0 * Math.PI / 180);
    ar[i] = new pos(x, y);
  }
  this.path = ar;
  this.statement = (statement) ? statement : null;
  this.animate(interval);
}

This method slides the element in a circle. It enables you to choose the starting and ending angle, so you can move the element along a circular arc. Here's a complete rundown of its arguments:

Be prepared to jump back in time, because we're going to discuss some high school math. The function first subtracts the starting angle from the ending angle, and assigns the result to a local variable named dangle. We then divide the result by the value of steps to discover the angle incrementation (the number of degrees to move each time). As in slideTo(), we assign the element's current x and y coordinates to two local variables.

As you know (or at least remember from those aweful lessons in high school), the easiest way to define a circle is its radius and center coordinates. The radius is handed to the function as an argument, so we only need to calculate the coordinates of the center position. The following statements are responsible for that:

var cx = x - radius * Math.cos(angle0 * Math.PI / 180);
var cy = y + radius * Math.sin(angle0 * Math.PI / 180);

Enough math for today. We're not going to get ourselves into this mess, so it's up to you to understand the equations. Notice that the angle0 must be multiplied by Math.PI / 180, because JavaScript's trigonometric methods handle angles measured in radians (rather than degrees).

The remaining portion of the function is similar to the slideTo() method. If you need to refresh your memory, refer to our previous explanations. The only difference it the math (yes, again) in the loop.

https://www.internet.com


Created: April 21, 1998
Revised: April 21, 1998

URL: https://www.webreference.com/js/column18/circle.html