HTML and CSS Reference
In-Depth Information
Environmental boundaries
With any activity you're involved in—whether it's playing a sport, working at your job, building a house,
etc.—there's a space for that activity. This enables you to focus your attention on what happens in this
area and ignore, at least temporarily, events that take place outside this area.
If one of the objects in your zone of interest moves outside that space, you have a choice to make: move
the object back into the zone, or stop paying attention to the it. Another option is to follow the object, or
move the space so that it continues to enclose the object, even though it is moving. When programming
animations, these choices are not much different.
In your canvas animations, you set up a space for your objects. Generally, this is the whole canvas
element, but the area can be some portion of the canvas, or even a space that is larger than the canvas.
Because the objects are moving, there's a good chance that they will eventually leave that space. When
they leave, you can forget about them, move them back into the area, or follow them. In this chapter, we
cover strategies for the first two of these approaches. First, though, let's determine where the boundaries
are and how to specify them.
Setting boundaries
In most cases, a simple rectangle works as a boundary. Let's start with the easiest example, the
boundaries based on the size of the canvas. As in the examples so far, we access the HTML canvas
element using the DOM interface, specifying the element id , and then assign it to a variable:
var canvas = document.getElementById('canvas');
The top and left boundaries of the animation are zero, and the right and bottom boundaries are
canvas.width and canvas.height . You can store these in variables, like so:
var left = 0,
top = 0,
right = canvas.width,
bottom = canvas.height;
If you store the dimensions in variables like this, realize that their values will not change if the size of the
canvas element changes later. Use this if you have a fixed area for your boundaries. If you use the full
dimensions of the element, you can refer directly to the canvas.width and canvas.height properties in
your code.
Just because these examples use the full canvas area doesn't mean that you have to. For example, you
can make a “room” that an object stays within, setting up boundaries like the following: top = 100 ,
bottom = 300 , left = 50 , right = 400 .
With the boundaries in place, you can check all the moving objects you're tracking to see whether they're
still within this space. You can do this with a couple of if-else statements, and here is a simplified
version of what that looks like:
if (ball.x > canvas.width) {
// do something
} else if (ball.x < 0) {
 
Search WWH ::




Custom Search