HTML5 canvas Tutorial

About HTML5 Canvas

The <canvas> tag is one of the most interesting HTML5 features.
The <canvas> element itself is quite simple, defining the width, height, and unique ID for the object. The developer must then use a series of JavaScript APIs to draw objects on the canvas.
The example below shows the basic structure of implementing the canvas:

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Page Title</title>
<script type="text/javascript">
function draw() {
  // get a reference to the <canvas> tag
  var canvas = document.getElementById("id_canvas");

  // if the browser support canvas
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
    // Apply JavaScript APIs for drawing
  }
}

// calls the draw() function when the page finished loading
window.onload = draw;
</script>
</head>
<body>

<canvas id="id_canvas" width="200" height="200"></canvas>

</body>
</html>
- Width and height attributes specify the size of the CANVAS space on the screen.
- It is the ID that is important (here the ID is "id_canvas"), you use it in JavaScript to get a reference to the <canvas> (with document.getElementById('ID')), then you can apply specific functions and properties to create drawings that will appear in the CANVAS tag.
- The getContext('2d') method must be applied to the canvas element, to get an object at which will be applied API instructions to create the context in <canvas>.

<canvas> is a block type element, can be added within any other block tag, like <p>, <div>, or into the new structure elements introduced in HTML5: <section>, <article>.

Drawing with HTML5, canvas and JavaScript

The JavaScript APIs allow the developer to draw shapes and lines; apply color, opacity, and gradients; create text; transform canvas objects; and perform animation.
  - The example below draws a blue box
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Canvas blue box</title>
<script type="text/javascript"><!--
function draw() {
  var canvas = document.getElementById('cav1');

  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
    ctx.fillStyle = '#0101fe';
    ctx.fillRect (50, 60, 100, 100);
  }
}

window.onload = draw;      // calls the draw() function when the page finished loading
--></script>
</head>
<body>
<canvas width="200" height="200" id="cav1"></canvas>
</body>
</html>
Result:
HTML5 Canvas blue box

- Syntax:
You can create more complex drawings, combining circles, lines, gradient, transparency.
- Becouse many users still use browser that not recognizes the CANVAS element, you can add a text with a no-canvas error message within a tag with "display:none", and use JavaScript to make that tag visible in case of an unsupported browser.

- If you add the JavaScript below the canvas element, you don't need the window.onload; just simply call the function with the APIs. You'll see in the next examples.

Adding transparency

To add transparency, define the color using the rgba(Red, Green, Blue, Opacity) format. "Opacity" is a value between 0 and 1 that represents the transparency.
Let's introduce another box, but with opacity of 50%. In this case we define "fillStyle" for the second shape, using rgba() to specify an alpha (or opacity) value along with the color ( rgba(220, 223, 0, 0.5) ).
Also we add a no-canvas message and write the JavaScript below the <canvas> tag (to not use window.onload).
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Canvas opacity</title>
</head>
<body>
<canvas width="200" height="200" id="cav1"></canvas>
<p id="no_cav" style="display:none;">You need a Canvas-compatible browser to view canvas area.</p>
<script type="text/javascript"><!--
function draw() {
  var canvas = document.getElementById('cav1');

  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
    ctx.fillStyle = '#0101fe';
    ctx.fillRect (50, 60, 100, 100);
    ctx.fillStyle = "rgba(220,223,0, 0.5);";
    ctx.fillRect (90, 105, 100, 80);
  }
  else {
    // make the element with the no-canvas message visible
    document.getElementById('no_cav').style.display = 'block';
  }
}

draw();     // calls the function to execte the drawing APIs
--></script>
</body>
</html>
Result:
Canvas transparency

Drawing lines

To draw lines, use the lineTo() function.
lineTo(x, y)
This method define a line from the starting current point till the coordinates (x, y).
To set or move the starting point for drawing, use the moveTo() method.
moveTo(x, y)
- This method creates a new subpath (a starting point) with the given point.

To define a color for the line, use:     ctx.strokeStyle = "color";
To define the thickness of the line (in pixels), use:     ctx.lineWidth = value;

The following code creates three lines.
<canvas width="200" height="200" id="cav1"></canvas>
<p id="no_cav" style="display:none;">You need a Canvas-compatible browser to view canvas area.</p>
<script type="text/javascript"><!--
function draw() {
  var canvas = document.getElementById('cav1');

  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    // define line color and width
    ctx.strokeStyle = '#01da01';
    ctx.lineWidth = 3;

    // create the first line
    ctx.moveTo(10, 10);           // sets the start point
    ctx.lineTo(100, 80);          // define a line till these coordinates

    // create the second line
    ctx.moveTo(10, 10);           // sets the start point
    ctx.lineTo(120, 120);         // define a line till these coordinates

    // the third line
    ctx.moveTo(10, 150);           // moves start point
    ctx.lineTo(140, 150);

    ctx.stroke();       // draw the strokes
  }
  else {
    // make the element with the no-canvas message visible
    document.getElementById('no_cav').style.display = 'block';
  }
}

draw();     // calls the function to execute the drawing APIs
--></script>
After we define the color of the line (with strokeStyle), and the thickness (with lineWidth), we use the moveTo() method to set the start point, then with lineTo(100, 80) we draw a line till the (100, 80) point coordinate.
Now, the last point becomes the current starting point, to move it, we use again the moveTo() method.
The code above will display the following result (in a Canvas-compatible browser):
HTML5 Canvas line

Drawing arcs and circles

To draw arcs and circles, we use the arc() function.
Syntax:
arc(x, y, radius, startAngle, endAngle, anticlockwise)
- This method draws an arc between the startAngle and endAngle, going anti-clockwise if the anticlockwise argument is true, and clockwise otherwise.
To draw a circle, set startAngle=0, endAngle=Math.pi*2

After you define the arc (or circle) with the arc() method, apply:
    ctx.stroke();   - to draw the margin /border.
    ctx.fill();   - to add the fill color.

The next example draws a smiling face.
<canvas width="200" height="200" id="cav1"></canvas>
<p id="no_cav" style="display:none;">You need a Canvas-compatible browser to view canvas area.</p>
<script type="text/javascript"><!--
function draw() {
  var canvas = document.getElementById('cav1');

  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
    ctx.arc(75,75,50,0,Math.PI*2,true);     // Face
    ctx.moveTo(110,75);
    ctx.arc(75,75,35,0,Math.PI,false);      // Mouth
    ctx.moveTo(65,65);
    ctx.arc(60,65,4,0,Math.PI*2,true);     // Left eye
    ctx.moveTo(95,65);
    ctx.arc(90,65,4,0,Math.PI*2,true);     // Right eye
    ctx.stroke();
  }
  else {
    // make the element with the no-canvas message visible
    document.getElementById('no_cav').style.display = 'block';
  }
}

draw();     // calls the function with drawing APIs
--></script>
The drawing starts by 1st drawing the face, followed by moving to the end of the mouth and then drawing that, and so forth. The moveTo() function takes care of moving from one coordinate to another.
Result:
Canvas smiling face

Canvas - Text

You have two methods for drawing text in canvas:
The following text properties are available on the context object:
Example:
<canvas width="200" height="200" id="cav1"></canvas>
<p id="no_cav" style="display:none;">You need a Canvas-compatible browser to view canvas area.</p>
<script type="text/javascript"><!--
function draw() {
  var canvas = document.getElementById('cav1');

  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    // create text with fill color
    ctx.fillStyle = '#00f';
    ctx.font = 'italic 30px sans-serif';
    ctx.textBaseline = 'top';
    ctx.fillText('Hy everyone', 2, 5);

    // create text without fill color
    ctx.font = 'bold 30px sans-serif';
    ctx.strokeText('Hy everyone', 2, 50);
  }
  else {
    // make the element with the no-canvas message visible
    document.getElementById('no_cav').style.display = 'block';
  }
}

draw();     // calls the function with drawing APIs
--></script>
Result:
HTML5 Canvas text

Canvas - Shadows

The Shadow API gives you four properties that are applied to context object:
The next code draws a blue sphere with a green shadow having 50% transparency:
<canvas width="200" height="200" id="cav1"></canvas>
<p id="no_cav" style="display:none;">You need a Canvas-compatible browser to view canvas area.</p>
<script type="text/javascript"><!--
function draw() {
  var canvas = document.getElementById('cav1');

  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    // sets shadow properties
    ctx.shadowOffsetX = 8;
    ctx.shadowOffsetY = 8;
    ctx.shadowBlur = 4;
    ctx.shadowColor = 'rgba(0, 200, 1, 0.5)';

    // define and add a circle
    ctx.fillStyle = '#0000fe';
    ctx.arc(75,75,50,0,Math.PI*2,true);
    ctx.fill();
  }
  else {
    // make the element with the no-canvas message visible
    document.getElementById('no_cav').style.display = 'block';
  }
}

draw();     // calls the function with drawing APIs
--></script>
Result:
HTML5 Canvas shadow

Canvas - Gradient

To create gradients in Canvas, you assign a CanvasGradient object to the fillStyle and strokeStyle properties.
You can create two types of CanvasGradient object, using one of the following methods:
Once you have the gradient object you can add color stops along the gradient using the addColorStop() method of the object. The following two codes shows you how to use gradients.
  1) Example with createLinearGradient():
<canvas width="200" height="200" id="cav1"></canvas>
<p id="no_cav" style="display:none;">You need a Canvas-compatible browser to view canvas area.</p>
<script type="text/javascript"><!--
function draw() {
  var canvas = document.getElementById('cav1');

  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    // create a Linear CanvasGradient object
    // provide the source, the start and end (x0, y0, x1, y1) coordinates
    var gradient = ctx.createLinearGradient(0, 0, 150, 0);

    // Now add colors in your gradient, the first argument tells the position for the color
    // - accepted value range is from 0 (gradient start) to 1 (gradient end)
    // The second argument tells the color you want, using the CSS color format
    gradient.addColorStop(0,   '#f00');        // red
    gradient.addColorStop(0.4, '#ff0');        // yellow
    gradient.addColorStop(0.8, '#0f0');        // green
    gradient.addColorStop(1,   '#00f');      // blue
    

    // Apply the gradient to fillStyle property, and draw an rectangle
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, 200, 125);
  }
  else {
    // make the element with the no-canvas message visible
    document.getElementById('no_cav').style.display = 'block';
  }
}

draw();
--></script>
Result:
Canvas linear gradient

  2) Example with createRadialGradient():
<canvas width="200" height="200" id="cav1"></canvas>
<p id="no_cav" style="display:none;">You need a Canvas-compatible browser to view canvas area.</p>
<script type="text/javascript"><!--
function draw() {
  var canvas = document.getElementById('cav1');

  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    // create a Radial CanvasGradient object
    // provide the source, the start, end and radius (x0, y0, r0, x1, y1, r1) of the circles
    var gradient = ctx.createRadialGradient(70, 80, 10, 78, 75, 45);

    // Adding colors to a radial gradient is the same as adding colors to linear
    gradient.addColorStop(0, '#0f0');
    gradient.addColorStop(0.5, '#fff');
    gradient.addColorStop(1,   '#00f');
    

    // Apply the gradient to fillStyle property, and draw an circle
    ctx.fillStyle = gradient;
    ctx.arc(75,75,50,0,Math.PI*2,true);
    ctx.fill();
  }
  else {
    // make the element with the no-canvas message visible
    document.getElementById('no_cav').style.display = 'block';
  }
}

draw();
--></script>
Result:
Canvas radial gradient

HTML5 Canvas - Inserting images

To insert images in a <canvas>, use the drawImage() method. It is a complex method that uses three, five, or nine arguments.
Here's the syntax with five arguments:
drawImage(img_element, dx, dy, dw, dh)
- The first argument, img_element represents the reference to an image, "dx" and "dy" specify the destination coordinates inside your canvas context, "dw" and "dh" specify the width and height of the inserted image (in cases where you want to resize it).
- The variant with nine arguments can be used to crop the image, it adds four more arguments that set the coordinates (x0, y0, x1, y1) for the crop area.

In the following example we insert this image: HTML5 course in a <canvas> (resizing it), and a text next to it.
<canvas width="260" height="200" id="cav1"></canvas><br />
<p id="no_cav" style="display:none;">You need a Canvas-compatible browser to view canvas area.</p>
<img src="html_course.jpg" alt="HTML course" width="152" height="160" id="img1" />
<script type="text/javascript"><!--
function draw() {
  var canvas = document.getElementById('cav1');

  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    // get a reference to the image, then adds it in canvas context (resizing it)
    var img_elm = document.getElementById('img1');
    ctx.drawImage(img_elm, 0, 0, 95, 100);

    // add a text without fill color
    ctx.font = 'bold 25px sans-serif';
    ctx.textBaseline = 'top';
    ctx.strokeText('HTML Course', 98, 38);
  }
  else {
    // make the element with the no-canvas message visible
    document.getElementById('no_cav').style.display = 'block';
  }
}

draw();
--></script>
Result:
HTML5 Canvas image

• The JavaScript APIs also allow the <canvas> to be interactive and respond to user input such as mouse events and key events, facilitating the production of games and Web applications on the canvas.
- In the next example we use "onmouseover", "onmouseout", and "onclick" events, to change the color of a rectange in <canvas>.
<canvas width="121" height="81" id="cav1" onmouseover="draw('#fefe01');" onmouseout="draw('#01de02');" onclick="draw('#fe0708');" style="cursor:pointer;"></canvas>
<p id="no_cav" style="display:none;">You need a Canvas-compatible browser to view canvas area.</p>
<script type="text/javascript"><!--
function draw(clr) {
  var canvas = document.getElementById('cav1');

  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    // draw a rectangle, using a fill color defined in "clr" parameter
    ctx.fillStyle = clr;
    ctx.fillRect (0, 0, 120, 80);
  }
  else {
    // make the element with the no-canvas message visible
    document.getElementById('no_cav').style.display = 'block';
  }
}

draw('#0102fe');        // calls the function
--></script>
The "fillStyle" property uses the color passed in parameter, so when we call the draw() function with differen color in argument, the color of the rectangle changes.
To see the effect, move the mouse over the rectangle below, then click on it.
 

There are many other JavaScript properties and methods for Canvas. For a complete documentation about canvas, see the HTML Canvas 2D Context.