HTML and CSS Reference
In-Depth Information
After that, we discuss time-based animation, a technique that can be used with either frames or timers.
Timer-based animation
The JavaScript functions used for timer-based animations are window.setTimeout and
window.setInterval . Each takes the same two arguments: a function to execute, and a number
specifying the amount of milliseconds to wait before running that function.
function printMessage () {
console.log("Hello, Timer!");
}
window.setTimeout(printMessage, 2000);
Here, the printMessage function is passed to the window.setTimeout and set to run in 2000
milliseconds. Once you execute this code, wait 2 seconds (1000 milliseconds is 1 second) and the
message prints to the debugging console.
window.setInterval also executes a function, but instead of calling it once, it keeps running it again and
again at the specified interval (unless you tell it to stop).
Setting up a timer-based canvas animation isn't much different than the other examples in this topic that
use window.requestAnimationFrame . You set up an interval for the frame rate and the timer runs the
animation loop. Here's a simple example (document 11-timer.html) :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Timer</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(),
fps = 30;
ball.y = canvas.height / 2;
ball.vx = 5;
function drawFrame () {
context.clearRect(0, 0, canvas.width, canvas.height);
ball.x += ball.vx;
ball.draw(context);
}
 
Search WWH ::




Custom Search