HTML and CSS Reference
In-Depth Information
Let's try it out. In the next example, use the Ball class we used in the Chapter 5, with a small addition.
Add vx and vy properties to it, so that each ball keeps track of its own velocity. Here it is in its entirety:
function Ball (radius, color) {
if (radius === undefined) { radius = 40; }
if (color === undefined) { color = "#ff0000"; }
this.x = 0;
this.y = 0;
this.radius = radius;
this.vx = 0;
this.vy = 0;
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();
context.arc(0, 0, this.radius, 0, (Math.PI * 2), true);
context.closePath();
context.fill();
if (this.lineWidth > 0) {
context.stroke();
}
context.restore();
};
The following example, 01-removal.html , sets up a number of these balls and removes them when they
move off the canvas:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Removal</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<textarea id="log"></textarea>
<script src="utils.js"></script>
<script src="ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
Search WWH ::




Custom Search