ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

HTML5 Canvas Tutorial

Updated on January 9, 2013
Source

(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.


Object
Description
canvas
This is the base objects for rendering images and graphics in a web document
canvasGradient
Represents the image fillStyle and canvasRenderingContext2D
canvasImageData
Represents a rectangle (CSS height and width) of an image
canvasPattern
Represents a pattern for the fillStyle
canvasPixelArray
Data returned by canvasImageData on color and alpha for RGBA
canvasRenderingContext2D
Represents the object of origin 0,0 from the upper left corner.
canvasTextMetrics
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--> 
<body>
        <!--[if lt IE 7]>
            <p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p>
        <![endif]-->

        <!-- 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>
        
       
    </body>

Canvas Demo 1 - drawLines

var canvas;


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

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)

<body>
        <!--[if lt IE 7]>
            <p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p>
        <![endif]-->

        <!-- 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>
       
    </body>

Canvas Demo 2 - Interactive Mode (Javascript)

function enableEvents(){
	canvas = document.getElementById("testCanvas");
	if ('ontouchstart' in document.documentElement) {
  			canvas.addEventListener("touchstart", interactive, false);
	}else{
			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.beginPath();
    	context.moveTo(x, y);
   		isDrawing = true;
  	  } else {
    	context.lineTo(x, y);
    	context.stroke();
  	}
	
	var radius = 2;
	context.arc(x,y,radius,0,2*Math.PI,false);
	
    context.fill();	
}

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


Comments

    0 of 8192 characters used
    Post Comment

    • klanguedoc profile imageAUTHOR

      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!

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)