ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Computer Programming Tutorials

HTML5 Canvas Tutorial

Updated on January 9, 2013

(c) 2013 kevin languedoc (klanguedoc)

One of the most sought after and a component that led to the demise, to some extent, of Flash was the canvas specification, along with Audio and Video. canvas is an element that lets developer create graphics. That right, with canvas, developers can render 2D and 3D graphics right in a web page just like Flash and Silverlight (XAML). With canvas and for browsers that support this important HTML5 addition, developers can implement the WebGL API. The WebGL is a Javascript port of the powerful openGL 2d and 3d graphics library. Already several well known and sophisticated video game have been ported to HTML5 because of the canvas element and WebGL. Some of these include: Angry Birds (Rovio), Command & Conquer (AE), Quake 2 (id software), Wolfenstein 3D (id Software) to name a few.

The canvas element is a hosting mechanism for 2D and 3D graphics. You can use this element to draw graphics, like having a user sign a contract or some other document with their finger (on a touch screen) or a pointing device, you could draw complete drawings using proper input devices and the programming of drawing tools and you can also render high quality graphics using libraries like the openGL or WebGL.

The canvas is quite vast and is unfeasible to attempt to document the API in a single tutorial or reference document such as this. However a tutorial can demonstrate some of canvas’ more important or main features. So this tutorial will demonstrate how to use the canvas element to draw some basic graphic images.

All modern browsers support the canvas element.

How It Works

The canvas element of the HTML5 API is a resolution-dependent bitmap rendering tool for graphs, 2d and 3d graphics, line art and other graphic representations that are rendered in real time.

The canvas element can operate in two broad modes: interactive and noninteractive. In an interactive capacity, the canvas element needs to have scripting enabled which would allow an user to create graphics directly in the canvas element on the web page. The embedded content is rendered in whole or in part by the user. In contrast, the non interactive mode, the user is a passive viewer of the live embedded content in the canvas.

There 7 canvas objects, each provided a unique capability for rendering 2d or 3d graphics. In order to draw graphic objects, you need to get the canvas object and then get the context from the canvas element using the getContext and assign it to the context variable. The example provide detail code on the approach.

This is the base objects for rendering images and graphics in a web document
Represents the image fillStyle and canvasRenderingContext2D
Represents a rectangle (CSS height and width) of an image
Represents a pattern for the fillStyle
Data returned by canvasImageData on color and alpha for RGBA
Represents the object of origin 0,0 from the upper left corner.
Represents the width attribute from the textMetric method

With the canvas element, javascript API you can create a wide selection of graphic objects, lines, charts and graphs, animations and interacting with embedded graphics and animations. You can use and manipulate the basic drawing tools in the API which include

  • rectangles
  • arcs
  • paths and line drawings
  • bezier and quadratic arcs

In addition to these objects, several special effects can be applied to allow you to transform these basic objects. You can apply these transformations to your objects:

  • scaling
  • rotations
  • transformation matrices
  • translations

For effects, you can use fills, strokes, shadows, gradients, transparencies and compositing as required via Javascript scripting with the API or by allowing users to use these tools, effects and transformation interactively using the HTML DOM events through Javascript. All of these manipulations and object creations can be done without using CSS3.

Rendering Examples

The following examples will demonstrate how the canvas works in both a non interactive fashion as well as an interactive fashion. The first example draws a simple line in a rectangle using the beginPath, moveTo, lineTo and stroke. Finally the rectangle is filled with a blue background.

Canvas Demo 1 - Drawing a Line

....<!--truncated for brevity--> 
        <!--[if lt IE 7]>
            <p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="">activate Google Chrome Frame</a> to improve your experience.</p>

        <!-- Add your site or application content here -->
        <p>This is a demo of the Canvas HTML5 element</p>

        <script src="js/main.js"></script>
         <button name="drawLines" value="" onclick="drawLines()">Draw Lines</button><br/>
        <canvas id="testCanvas" width="500" height="300"></canvas>

Canvas Demo 1 - drawLines

var canvas;

function drawLines(){
	canvas = document.getElementById("testCanvas");
	var context = canvas.getContext("2d");
      	context.moveTo(120, 175);
      	context.lineTo(450, 50);
      	 // Now fill with a solid color
              context.fillRect(0, 0, 300, 250);
              context.fillStyle = "blue";
              context.fillRect(250, 300, 600, 500);

The second example demonstrates how to use your mouse to create lines on the canvas. To produce this functionality I am following the following process depending on the type of input device. For desktop apps, you can use the mousedown, mousemove and mouseup DOM events. For mobile devices like the Android and iOS, you can use the touchstart and touchend events in the WebKit engine (this is the engine in Safari and Chrome).
Detect initial x and y coordinates from pointing device or finger

  1. Get the canvas element id
  2. Get the context
  3. Get the x and y coordinates
  4. Set the output div (optional) value of the x and y value
  5. Set fill color
  6. Call the beginPath
  7. Call the moveTo as the mouse or finger moves
  8. Fetch x and y as the mouse or finger moves
  9. Set new coordinates
  10. Set the fill style, like an arc (radius)
  11. Set fill color
  12. Call the fill method to draw the arc (radius) on screen

Canvas Demo 2 - Interactive Mode (HTML)

        <!--[if lt IE 7]>
            <p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="">activate Google Chrome Frame</a> to improve your experience.</p>

        <!-- Add your site or application content here -->
        <p>This is a demo of the Canvas HTML5 element</p>

        <script src="js/main.js"></script>
         <button name="drawLines" value="" onclick="drawLines()">Draw Lines</button>
         <button name="drawInteractiveLines" value="" onclick="enableEvents()">Interactive Lines</button><br/>
        <canvas id="testCanvas" width="500" height="300"></canvas>
        <p>Current x coordinate: <div id="xoutput"></div></p>
        <p>Current y coordinate: <div id="youtput"></div></p>

Canvas Demo 2 - Interactive Mode (Javascript)

function enableEvents(){
	canvas = document.getElementById("testCanvas");
	if ('ontouchstart' in document.documentElement) {
  			canvas.addEventListener("touchstart", interactive, false);
			canvas.addEventListener("mousemove", interactive, false);

Canvas Demo 2 - Interactive Mode (interactive method)

function interactive(evt){
	var isDrawing = false;
	canvas = document.getElementById("testCanvas");
	var context = canvas.getContext("2d");
	var x =  evt.pageX - canvas.offsetLeft;
	var y = evt.pageY - canvas.offsetTop;
	var xout = document.getElementById("xoutput");
	var yout = document.getElementById("youtput");
	context.fillStyle = 'black';
	xout.innerHTML = x;
	yout.innerHTML = y;
	 if (!isDrawing) {
    	context.moveTo(x, y);
   		isDrawing = true;
  	  } else {
    	context.lineTo(x, y);
	var radius = 2;

These are very simplistic examples but I hope they provide you with enough detail to help implement your own solutions.


    0 of 8192 characters used
    Post Comment

    • klanguedoc profile image

      Kevin Languedoc 5 years ago from Canada

      I'm so happy. Thanks a lot.

    • Saloca profile image

      Saloca 5 years ago from Liverpool, UK

      Very useful up and well written/set out! Great job!