HTML5 and CSS3

<7> HTML5 Canvas </7>

Content

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>
<html>
<head>
<meta charset="utf-8" />
<title>Canvas example</title>
<script>
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;
</script>
<body>
<canvas></canvas>
</body>
</html>

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:

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

Canvas properties

Canvas methods

Some of the most important canvas methods:

More information: