MOBILE

Programming the Mobile Web : HTML 5 (part 2) - The canvas Element

1/24/2011 11:40:37 AM

5. The canvas Element

The possibility of a drawing API was the dream of every web designer in the ’90s, but it has only recently become available in browsers. canvas is an HTML element that defines a rectangular area where we can draw using a JavaScript API. The drawings are not vector-based, and we cannot browse through them using DOM or any other mechanism. canvas is not a competitor for SVG; it’s just another way to generate dynamic graphics in a browser window.


Note:

canvas was originally defined by Apple in WebKit, and it is the oldest HTML 5 feature in the web developers’ world. You will find a lot of resources on the Web on the usage of this element.


The only mandatory attributes are an id and the dimensions width and height:

<canvas width="300" height="300" id="canvas">
Here goes text, images, or other tags for noncompatible browsers
</canvas>

5.1. The context

Once we have defined a canvas we get what is called a 2D context: a JavaScript object that we can use for drawing bitmaps over that canvas.


Note:

Some desktop browsers add support for a very experimental 3D context, where we can draw in 3D coordinates and the browser renders the graphics. This is not available yet in mobile browsers.


We can get the context pointer using the following code, with the code checking for API support first:

var canvas = document.getElementById('canvas');
if (canvas.getContext) {
// canvas is supported
var context = canvas.getContext('2d');
}

5.2. Lines and strokes

Once we have the context, we can define the line type using the color properties fillStyle and strokeStyle and the integer property lineWidth. Then we can start drawing.

5.3. Drawing methods

The available drawing methods of the 2D context are listed in Table 2.

Table 2. Drawing methods in the HTML 5 canvas context
MethodDescription
fillRect(x, y, width, height)Draws a filled rectangle with the current styles.
strokeRect(x, y, width, height)Draws a stroked rectangle with a transparent fill.
clearRect(x, y, width, height)Clears the area and makes it transparent.
beginPath()Begins a path drawing.
closePath()Closes the shape by creating a line from the first path line to the ending path line.
moveTo(x, y)Moves the pen to the coordinates for the next line in the path.
lineTo(x, y)Draws a line from the current pen coordinates to the ones provided.
arc(x, y, radius, startAngle, endAngle, anticlockwise)Draws an arc with its center at x, y and with the defined radius. The anticlockwise parameter is a Boolean value. Angles are defined in radians.
quadraticCurveTo(controlx, controly, x, y)Draws a quadratic bezier curve.
bezierCurveTo( control1x, control1y, control2x,control2y, x, y) Draws a cubic bezier curve.
stroke()Draws the path defined since the last beginPath().
fill()Closes the path defined since the last beginPath() and fills it.
drawImage(x, y)Draws an image (Image JavaScript object) on the canvas. Other optional parameters also exist.
createImageData(width, height)Creates an ImageData object with a data attribute that is an array of pixels to be manipulated as integers.
getImageData(x, y, w, h)Gets an ImageData object from the current drawing to be manipulated.
putImageData(image_data, x, y)Puts an ImageData object into the drawing.
strokeText(string, x, y)Draws a stroked string.
fillText(string, x, y)Fills a string.

An excellent example of drawing curves on a canvas is provided by Mozilla’s documentation, which shows how to draw a dialog box with the following code:

context.beginPath();
context.moveTo(75,25);
context.quadraticCurveTo(25,25,25,62.5);
context.quadraticCurveTo(25,100,50,100);
context.quadraticCurveTo(50,120,30,125);
context.quadraticCurveTo(60,120,65,100);
context.quadraticCurveTo(125,100,125,62.5);
context.quadraticCurveTo(125,25,75,25);
context.stroke();


Warning:

Remember that angles in the Canvas API are defined in radians, not degrees. To make the conversion we can use the formula (Math.PI/180)*degrees.


5.4. Advanced features

Some other advanced features for canvases include text shadowing, gradients, image scaling, transparency, fonts, line styles, patterns, and other drawing methods. Not all presently work with all canvas-compatible browsers, so running tests like the one shown in Figure 9-8 is important.

Figure 1. A nice canvas drawing sample created using only a few lines of code.


5.5. Canvas compatibility

Table 3 lists browser support for basic canvas functionality. For more information, samples, and code for canvas, visit http://www.mobilexweb.com/go/canvas.

Table 3. HTML 5 canvas compatibility table
Browser/platformCanvas support
SafariYes
Android browserYes
Symbian/S60No
Nokia Series 40No
webOSYes, with partial text support
BlackBerryNo
NetFrontNo
Internet ExplorerNo
Motorola Internet BrowserNo
Opera MobileYes
Opera MiniYes, rendered on the server

Other  
  •  Windows Phone 7 : Submitting Your First Windows Phone Application to the Windows Phone Marketplace
  •  Windows Phone 7 : Packaging, Publishing, and Managing Applications
  •  Mobile Application Security : Windows Mobile Security - Development and Security Testing (part 3)
  •  Mobile Application Security : Windows Mobile Security - Development and Security Testing (part 2)
  •  Mobile Application Security : Windows Mobile Security - Development and Security Testing (part 1)
  •  Programming the Mobile Web : Mobile Rich Internet Applications (part 2) - JavaScript Mobile UI Patterns
  •  Programming the Mobile Web : Mobile Rich Internet Applications (part 1) - JavaScript UI Libraries
  •  Windows Mobile Security - Kernel Architecture
  •  Windows Mobile Security - Introduction to the Platform
  •  iPhone Programming : Table-View-Based Applications - Building a Model
  •  Mobile Application Security : The Apple iPhone - Push Notifications, Copy/Paste, and Other IPC
  •  Mobile Application Security : The Apple iPhone - Networking
  •  Windows Phone 7 Development : Handling Device Exceptions
  •  Registering a Windows Phone Device for Debugging
  •  Programming the Mobile Web : WebKit CSS Extensions (part 5) - Transformations
  •  Programming the Mobile Web : WebKit CSS Extensions (part 4) - Animations
  •  Programming the Mobile Web : WebKit CSS Extensions (part 3) - Transitions
  •  Programming the Mobile Web : WebKit CSS Extensions (part 2) - Reflection Effects & Masked Images
  •  Programming the Mobile Web : WebKit CSS Extensions (part 1) - WebKit Functions & Gradients
  •  Windows Phone 7 Development : Debugging Application Exceptions (part 2) - Debugging a Web Service Exception
  •  
    Most View
    Windows Server 2008 : Manipulating Services with wmic
    2012 Make It Worth ( Part 1)
    Tasmania - Ideal Destination For Landscape Photographers (Part 1)
    XNA Game Studio 4.0 : Gamer Services - Gamers and Profiles
    Buffalo Linkstation Pro 2TB
    jQuery 1.3 : Selectors - DOM traversal methods, Accessing DOM elements
    Devolo dLAN 500 AV Wireless+ - Is This The Ultimate Homeplug?
    5 Mid-Class Android Smartphones Value For Money
    The new Apple TV Box
    Ivy League All Stars : Acer Aspire S5, Apple MacBook Air, Samsung 900X4C
    Top 10
    NZXT Phantom 630 Modular Full Tower Case
    Rosewill Launches Armor Evolution Mid-Tower Case
    Windows 8 - An In-Depth Expert Review (Part 6)
    Windows 8 - An In-Depth Expert Review (Part 5)
    Windows 8 - An In-Depth Expert Review (Part 4)
    Windows 8 - An In-Depth Expert Review (Part 3)
    Windows 8 - An In-Depth Expert Review (Part 2)
    Windows 8 - An In-Depth Expert Review (Part 1)
    Kobo Mini: Does The World Need A Smaller E-Reader? (Part 2)
    Kobo Mini : Does The World Need A Smaller E-Reader? (Part 1)