HTML and CSS Reference
In-Depth Information
window.setInterval(drawFrame, 1000/fps);
};
</script>
</body>
</html>
In this example, the animation loop is set to run at 30 frames per second using a timer. But since there is
no way to accurately determine how fast the code will execute on the end user's machine, a timer-based
animation winds up being no more accurate than a frame-based animation. You might not see a difference
in a simple example like this one, but in a more processor intensive program, you will see a difference
across computers.
If you really need accuracy, time-based animation is the way to go.
Time-based animation
Time-based animation is the method to use if the speed of objects in your animation needs to be
consistent, which might be the case in some types of games. Neither frame- nor timer-based animation
can be counted on for a specific rate of playback. A complex animation on an older, slower computer might
run at a much lower speed than it was designed for. As you see shortly, when you use a time-based
animation, you get speed you can count on, no matter the frame rate of the animation.
The first thing you need to do is change the way you think about velocity. Up to now, when you saw
something like vx = 5 , the units you used were pixels per frame. In other words, the object moved 5
pixels on the x-axis each time a new frame was encountered. In a timer-based animation, it is 5 pixels per
timer interval.
For a time-based animation, you use real measurements of time, such as seconds. Because you deal with
a whole second, rather than a small fraction of one, the value needs to be much higher. If something
moves at 10 pixels per frame at 30 frames per second, that is roughly 300 pixels per second. For the next
example, we take the 05-bouncing-2.html exercise from Chapter 6 and make a few changes, which are
shown in bold (and can also be found in 12-time-based-1.html ):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Time based 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'),
 
Search WWH ::




Custom Search