HTML5 Canvas


The <canvas> element is used to draw graphics, on the fly, on a web page. The element is only a container for graphics. You must use a script (usually JavaScript) to actually draw the graphics.

Create a Canvas
A canvas is a rectangular area on an HTML page, and it is specified with the <canvas> element. The markup looks like this:
  <canvas id="myCanvas" width="200" height="100"
    style="border:1px solid #000000;"></canvas>

Draw onto the Canvas with JavaScript
All drawing on the canvas must be done inside a JavaScript; e.g.,
  <script>
    var c   = document.getElementById( "myCanvas" );
    var ctx = c.getContext( "2d" );
    ctx.fillStyle = "#FF0000";
    ctx.fillRect( 0, 0, 150, 75 );
  </script>
  1. Find the <canvas> element:
       var  c = document.getElementById( "myCanvas" );
  2. Call its getContext( ) method, which is a built-in HTML5 object, with many properties and methods for drawing graphics:
       var  ctx = c.getContext( "2d" );
  3. The next two lines draw a red rectangle. The fillRect(x,y,w,h) method draws a rectangle filled with the current fill style and the fillStyle property can be a CSS color, a gradient, or a pattern.
       ctx.fillStyle = "#FF0000";
       ctx.fillRect( 0, 0, 150, 75 );

Demonstration
The following demonstration shows how the HTML5 script is displayed on the Web.

     


Review: HTML5 Canvas
Which statement is NOT true about HTML5 Canvas?
      HTML5 can NOT be used to draw a circle.
      JavaScript is usually used by HTML5 canvas to draw graphics.
      The <canvas> element is used to draw graphics on a web page.
      The <canvas> element is only a container for graphics.
Result: