HTML and CSS Reference
In-Depth Information
<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(),
vx = 0,
ax = 0.1;
ball.x = 50;
ball.y = 100;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
vx += ax;
ball.x += vx;
ball.draw(context);
}());
};
</script>
</body>
</html>
Here, you start with velocity ( vx ) being zero. The acceleration ( ax ) is 0.1. This is added to the velocity on
each frame, and then the velocity is added to the ball's position.
Test this example. You see that the ball starts moving very slowly. By the time it leaves the canvas, it's
zipping right along.
Now, let's get closer to the spaceship example and allow the ball to turn the acceleration off and on, and
even reverse it. You can use the cursor keys for this. You know how to listen for keyboard events from
Chapter 2, and you can find the key that caused that event by checking the keyCode property of the event
object that gets passed to the event handler. This is a numeric value that corresponds to the particular key
being pressed. For now, we are concerned about the left cursor key ( keyCode value 37) and the right
cursor key ( keyCode value 39), and use these to change the acceleration. Here's the code ( 07-
acceleration-2.html ):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Acceleration 2</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>
Search WWH ::




Custom Search