HTML and CSS Reference
In-Depth Information
This example creates an instance of the Ball class, adds it to the canvas, and sets up an animation loop
using the drawFrame function and window.requestAnimationFrame that causes the ball to bob up and
down, as seen in the document 02-bobbing-1.html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Bobbing 1</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'),
ball = new Ball(),
angle = 0;
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
ball.y = canvas.height / 2 + Math.sin(angle) * 50;
angle += 0.1;
ball.draw(context);
}());
};
</script>
</body>
</html>
First, you need to create an angle property and initialize it to 0. In the drawFrame function, you take the
sine of that angle and multiply it by 50. This gives you a range of values from 50 to -50. If you add that to
the height of the canvas divided by 2, your values will be from 250 to 150 (based on a 400-pixel high
canvas element). Make that the y position of the ball. Then add 0.1 to the angle for the next time around.
You get a smooth up and down motion.
Play around with the various values. You'll notice that changing the 0.1 to another value changes the
speed of the motion. This makes sense, because the faster or slower the angle is increasing, the faster or
slower the return values from Math.sin will go from 1 to -1. Obviously, changing the 50 changes how far
the ball moves, and changing the canvas.height / 2 to some other value changes the point that it
oscillates around. From this, you can abstract the values into variables like the following (showing the
additional or changed parts of the script):
Search WWH ::




Custom Search