HTML and CSS Reference
In-Depth Information
x = Math.random() * canvas.width;
y = Math.random() * canvas.height;
}
context.fillStyle = "#000000";
context.beginPath();
//x, y, radius, start_angle, end_angle, anti-clockwise
context.arc(x, y, 2, 0, (Math.PI * 2), true);
context.closePath();
context.fill();
}
};
</script>
</body>
</html>
The distribution for this example can be seen in Figure 19-10.
Figure 19-10. Random distribution within two circles using distance-based collision detection
Here, we test whether a point falls with a circle, but the concept is the same no matter the shape (taking
into account the limitations of collision detection described in Chapter 9). You generate the random
position first, and then test whether it falls within a predefined area using the appropriate collision detection
technique. The trade-off to this method is that you are potentially generating many more positions than you
actually need. This technique is not something you want to run every animation frame, but it can be useful
at the start of your program (for example, in a game, when you set up random starting positions for
enemies).
Timer- and time-based animation
In the topic examples so far, the animation is set up by placing the motion code within the drawFrame
function and using window.requestAnimationFrame to build a loop. This is the preferred method for
canvas-based animations, because web browsers can optimize this function for animation without
degrading performance in the rest of the browser. We discussed this in detail in Chapter 2.
But in the days before all the multimedia support found in today's browsers, JavaScript timers were the
only way to set up animations. This method uses intervals to control the animation playback rate, which we
look at next.
 
Search WWH ::




Custom Search