<canvas>
element is one of the most popular additions to the HTML5 standards. It is widely supported by popular browsers like Firefox, Chrome, Safari and Opera (Internet Explorer supports it in their IE9 beta version). This guide will explore the use of HTML5’s <canvas>
element through a fun example: bouncing a blue ball around.<canvas>
tag primarily allows you to render 2D shapes and images dynamically using math functions. Practical uses for this are things such as dynamic charts that are populated by data from a relational database like MySQL or web games that rely solely on open technologies (JavaScript/HTML).<canvas>
in HTML merely allows you to define a region in terms of width and height, everything else related to the actual drawing of the shapes is done through JavaScript via a full set of drawing functions and methods (collectively known as the Canvas 2D API).<canvas>
element through a hands-on approach, we will create a ball that will be bouncing around using HTML5 specifications and JavaScript.<canvas>
element inside the <body>
tag. Though we only have one <canvas>
element in our HTML for this example, I have still assigned an ID to it (myCanvas
) just to make it easier/quicker to select it later on via JavaScript. I also defined the element’s dimensions (width/height), however, you could just as well do that via CSS by targeting the #myCanvas
ID.onLoad
), we just call the init()
function. Note that it’s better to write unobtrusive JavaScript but I would like to keep this exploration brief, simple and as self-explanatory in code as possible.<canvas>
and HTML5 (latest Safari, Opera, Chrome, and Firefox versions) so that you can preview the code..arc
method (100, 100 — the first two arguments) with variables x
and y
, which we will then increment by an amount of dx
and dy
.draw()
and call it every 10ms using JavaScript’s setInterval()
function.draw()
function is called, it draws a circle at the new coordinates without removing the old ones. That’s how the getContext
object works so it’s not a bug; it doesn’t really move the circle and, instead, it draws a circle at the new coordinates each time the function is called.clearRect
method right at the start of our draw()
function so that it clears out the previous circle before it draws the new one.<canvas>
element.x
and y
are beyond the canvas dimensions, and if so, we need to reverse the direction by setting values of dx
and dy
to the negative values.