HTML and CSS Reference
In-Depth Information
centerY = canvas.height / 2,
radius = 50,
speed = 0.05;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
ball.x = centerX + Math.sin(angle) * radius;
ball.y = centerY + Math.cos(angle) * radius;
angle += speed;
ball.draw(context);
}());
};
</script>
</body>
</html>
You can create this document yourself or use the example file 08-circle.html , which has all the work
done for you. Verify that you have a perfect circle.
Notice that the range in both cases is the hypotenuse of the triangle, and it's equal to the radius of the
circle. Thus, we changed range to radius , to reflect that.
The code uses cosine to get the x position and sine to get the y position. You should get used to those
relationships. When coding animations, almost any time you are talking about x, you should immediately
think cosine, and you should almost always connect y with sine. In fact, spend as much time as you need
to fully understand that last bit of code. It is going to be one of the most useful tools in your animation
toolbox.
Elliptical movement
While circles are lovely, sometimes a perfect circle isn't exactly what you need. What you might be looking
for is more of an oval or ellipse. The problem is with the radius, it makes the ranges of the x motion and y
motion the same, which is why you get a circle.
To make a more oval shape, use different values for the radius when you calculate the x and y positions.
Let's call them radiusX and radiusY . Here's how they fit in to our document 09-oval.html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Oval</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 () {
 
Search WWH ::




Custom Search