HTML and CSS Reference
In-Depth Information
context.fill();
if (this.lineWidth > 0) {
context.stroke();
}
context.restore();
};
Ball.prototype.getBounds = function () {
return {
x: this.x - this.radius,
y: this.y - this.radius,
width: this.radius * 2,
height: this.radius * 2
};
};
We also add another utility function to the utils.js file we've been importing into our documents.
utils.containsPoint defines three parameters. The first is an object representing a rectangle with x , y ,
width , and height properties—just the kind Ball.getBounds() returns—and the second and third
arguments are x and y coordinates. The utils.containsPoint function determines whether the given
position falls within the boundaries of the rectangle and returns true or false accordingly. Here's the
simple, but useful, function we add to the utils.js file:
utils.containsPoint = function (rect, x, y) {
return !(x < rect.x || x > rect.x + rect.width ||
y < rect.y || y > rect.y + rect.height);
};
And here's a complete example using the updated Ball class and the utils.containsPoint function,
document 01-mouse-events.html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Mouse Events</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'),
context = canvas.getContext('2d'),
mouse = utils.captureMouse(canvas),
log = document.getElementById('log'),
ball = new Ball();
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
Search WWH ::




Custom Search