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 = 1;
ball.x = 50;
ball.y = 100;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
ball.x += vx;
ball.draw(context);
}());
};
</script>
</body>
</html>
In this example, first you set an x velocity ( vx ) of 1. Remember that is 1 pixel per frame, so on each frame,
the vx is added to the ball's x property. The window.onload function is called when the browser is ready
for us to work with the HTML document and goes through the business of getting the ball onto the canvas
and setting up the animation loop using drawFrame and window.requestAnimationFrame . On each
frame, the ball is placed 1 pixel to the right of where it was on the previous frame. Try it out. Pretty good
illusion of motion, eh?
Play around with it. Give it higher values for vx , or try some negative values and watch the object move in
the other direction. See whether you can make the object move on the y axis instead.
Velocity on two axes
Moving along two axes is simple. You define a vx and a vy , and then add the vx to the x property and the
vy to the y property on each frame. So, for each frame, the object is going to move so many pixels on the
x axis and so many pixels on the y axis.
The following example (02-velocity-2.html) demonstrates this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Velocity 2</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
 
Search WWH ::




Custom Search