HTML5 and CSS3

<7> HTML5 Canvas </7>


The new canvas element (<canvas>) of HTML5 provides an Application Programming Interface (API) for two-dimensional drawing—lines, fills, images, text, and so on. The canvas is only a container for graphics, a script (e.g., JavaScript) must be used to actually draw the graphics. Every pixel in the canvas can be controlled.

Here is a simple example of use of the canvas element:

<!DOCTYPE html>
<meta charset="utf-8" />
<title>Canvas example</title>
function draw()
  var ctx = document.querySelector("canvas").getContext("2d");
  // First square
  ctx.fillRect(10, 10, 50, 50);
  // Second square
  ctx.fillRect(100, 100, 50, 50);

window.onload = draw;

Canvas example

Any text inside the <canvas> element will be displayed in browsers that does not support <canvas>. Therefore, it can be used to offer a fallback option:

Your browser doesn't support &lt;canvas&gt; element.
Please, downdload and use one of the following browsers:
<li>Google Chrome</li>
<li>Mozilla Firefox</li>

Canvas properties

Canvas methods

Some of the most important canvas methods:

More information: