A Moving Ball with HTML5 canvas

Hello Everyone!
Today we are going to learn something about the HTML5 canvas tag. And the result we are trying to achieve is shown here at codepan, It would be a ball moving around a designated area. The complete code is also available here on github.

So let’s begin and create an HTML file called index.html (You could name it anything else, it doesn’t matter) and put the following code in that:

Now, if you open the above index.html file containing the code mentioned above in your browser, it would not display anything. Though, the canvas is there, we just can’t see it yet.

So, in order to make use of the canvas tag that we’ve already introduced, we need to make use of some javascript. Let’s paint the entire canvas area as black and then paint a circle on top of it. Let’s add below code in your <head> tag:

Now, if you reload/ reopen the index.html file, you should be able to see a circle drawn on a black background (of area 300 x 300).

Let’s fast forward to the final code and update the code between your script tags to below code and reload the page to get the final result:

Rate this post

Leave a Reply