HTML5 Canvas Demo Bouncing Ball Example
Besides tutorials web developers can also learn HTML5 with HTML5 examples.
Here is an HTML5 Canvas demo for web programmers using HTML5 canvas element and programming with Javascript.
This HTML5 example shows how to use javascript to draw bouncing ball within canvas element borders, how to animate bouncing ball within canvas element with time periods defined using Javascript setInterval() function.
Besides drawing on HTML page using canvas element and Javascript programming, the boing sound effect that happens when ball hits the canvas borders is played by using the HTML5 Audio element.
HTML5 Canvas demo example showing how to program bouncing ball in canvas element
First of all, place the below HTML5 canvas element in your HTML web page codes.
After you create Canvas element in HTML codes, add the below required Javascript codes for HTML5 Canvas demo with bouncing ball example.
Please note that when defined time period is completed the setInterval() javascript function calls the draw() function.
Draw javascript function first clears canvas element drawing area using context object clearRect() method.
After clearing canvas element drawing space, a new circle with inside filled with color is drawn using drawCircle() function.
As javascript programmers will realize, for creating bouncing ball animation on HTML5 Canvas element, we have to draw the ball each time at time interval is completed.
New position of the ball in canvas after time interval is completed is calculated by adding delta-x and delta-y movement amounts to the current position (x,y) of the ball on canvas. If the ball hits the canvas element borders, the delta-x or delta-y position change amount is reversed in direction by multiplying it with -1. This delta position changes are kept same until the ball hits the canvas borders next time.
I used the HTML5 audio element for playing bounce effect on HTML page.
I create audio element dynamically using Javascript. But since not all web browsers support all audio file formats, I first checked whether the web browser can play a specific sound file format.
If browser supports audio tag with .mp3 file format, I play the file.
If web browser does not support HTML5 audio with .mp3 format, I check if it can play .wav format. And so on.
In order to check if web browser is capable of playing audio file format, I use audio object canPlayType() method which returns true or false.