HTML and CSS Reference
In-Depth Information
context.lineWidth = this.lineWidth;
context.fillStyle = this.color;
context.beginPath();
context.rect(0, 0, this.width, this.height);
context.closePath();
context.fill();
if (this.lineWidth > 0) {
context.stroke();
}
context.restore();
};
You'll notice that we left off the getBounds method in the Box class. Since the rectangle objects already
contain the required properties, we can pass them directly to the utils.intersects function to test for a
collision.
In this next example, a box is created at the top of the canvas element and falls to the bottom. When the
box is placed, it falls down until it hits the bottom of the canvas or collides with another box. If it hits
another box, it positions itself so it is sitting right on top of it. Here's the code for document 02-
boxes.html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Boxes</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="box.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
boxes = [],
activeBox = createBox(),
gravity = 0.2;
function createBox () {
var box = new Box(Math.random() * 40 + 10, Math.random() * 40 + 10);
box.x = Math.random() * canvas.width;
boxes.push(box);
return box;
}
function drawBox (box) {
if (activeBox !== box && utils.intersects(activeBox, box)) {
activeBox.y = box.y - activeBox.height;
activeBox = createBox();
}
box.draw(context);
Search WWH ::




Custom Search