HTML and CSS Reference
In-Depth Information
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<textarea id="log"></textarea>
<script src="utils.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
mouse = utils.captureMouse(canvas),
log = document.getElementById('log'),
rect = {x: canvas.width / 2, y: canvas.height / 2};
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var dx = rect.x - mouse.x,
dy = rect.y - mouse.y,
dist = Math.sqrt(dx * dx + dy * dy);
//draw square
context.fillStyle = "#000000";
context.fillRect(rect.x - 2, rect.y - 2, 4, 4);
//draw line
context.beginPath();
context.moveTo(rect.x, rect.y);
context.lineTo(mouse.x, mouse.y);
context.closePath();
context.stroke();
//log output of distance value to screen
log.value = "distance: " + dist;
}());
};
</script>
</body>
</html>
Here, dx and dy are calculated by subtracting the current mouse position from rect 's position. The dist
value is displayed in the textarea element, and a line is drawn from the rectangle to the mouse location
(you find more on the canvas drawing API in Chapter 4).
Test the file and move your mouse around. A line connects it to the rectangle, and you get a constant
readout of the length of that line.
In later chapters when discussing collision detection, we mention some weaknesses with the generic
testing functions, and see how you can use the Pythagorean Theorem formula to create a distance-based
method of collision detection. This theorem is also useful in calculating forces such as gravity or springs,
where the force between two objects is proportional to the distance between them.
 
Search WWH ::




Custom Search