HTML and CSS Reference
In-Depth Information
x2 = x1 * cos - y1 * sin,
y2 = y1 * cos + x1 * sin;
ball.x = centerX + x2;
ball.y = centerY + y2;
});
The first version includes four calls to Math functions within the iteration, meaning that all four are
executed once for each object being rotated. The second version has just two calls to Math functions, both
outside the loop, so they are executed only once, regardless of how many objects there are. For example,
if you have 30 objects, you're looking at 120 function calls on each frame with the first version, as
compared to 2 with the second version—that's quite a difference!
In the previous example, you were able to place the sin and cos calculations outside the drawFrame
function because you were using a fixed angle. However in many cases, these angles of rotation may
change, and you'll need to recalculate the sine and cosine each time it changes.
To demonstrate these latest concepts, let's build an example where the mouse position is controlling the
speed of rotation of multiple objects. If the mouse is in the center of the canvas, no rotation happens. As it
moves to the left, the objects move faster and faster in a counterclockwise direction. As it moves to the
right, they rotate in a clockwise direction. This example will start out quite similarly to the previous one,
except you'll create multiple instances of Ball , storing them in an array named balls . Here's the
document ( 03-rotate-3.html ):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Rotate 3</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
mouse = utils.captureMouse(canvas),
balls = [],
numBalls = 10,
vr = 0.05,
centerX = canvas.width / 2,
centerY = canvas.height / 2,
cos, sin; //referenced by move and drawFrame
for (var ball, i = 0; i < numBalls; i++) {
ball = new Ball();
ball.x = Math.random() * canvas.width;
ball.y = Math.random() * canvas.height;
balls.push(ball);
Search WWH ::




Custom Search