HTML and CSS Reference
In-Depth Information
For velocity on one axis, you simply add the velocity to the object's position on that axis. Whatever your vx
is, you add it to the object's x property on each frame.
Let's see it in action. Many of the examples in this chapter (and in later chapters) need some kind of object
to move around. Rather than using valuable space drawing such an object in every script and example, we
make a Ball class that we can reuse. This class was first introduced in Chapter 3, but in case you didn't
keep it handy, here it is again. Include this code in the file ball.js , which we import into our main
document:
function Ball (radius, color) {
if (radius === undefined) { radius = 40; }
if (color === undefined) { color = "#ff0000"; }
this.x = 0;
this.y = 0;
this.radius = radius;
this.rotation = 0;
this.scaleX = 1;
this.scaleY = 1;
this.color = utils.parseColor(color);
this.lineWidth = 1;
}
Ball.prototype.draw = function (context) {
context.save();
context.translate(this.x, this.y);
context.rotate(this.rotation);
context.scale(this.scaleX, this.scaleY);
context.lineWidth = this.lineWidth;
context.fillStyle = this.color;
context.beginPath();
//x, y, radius, start_angle, end_angle, anti-clockwise
context.arc(0, 0, this.radius, 0, (Math.PI * 2), true);
context.closePath();
context.fill();
if (this.lineWidth > 0) {
context.stroke();
}
context.restore();
};
Now, any time we refer to this class, you should include this script in your main document, and you can
create a new ball by calling new Ball(size, color) .
Now that you have something to move, here's the first velocity example, document 01-velocity-1.html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Velocity 1</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
Search WWH ::




Custom Search