Tuesday, August 2, 2011



HTML5 <canvas> Part1 : Introduction

Hello all, this is my first blog post here on TOC and I'm excited to present this article on HTML5 <canvas> element. As you might know HTML5 has been around here for a fair amount of time now and since all major browsers support its semantics with very minor differences, many developers are now picking it as their preferred choice for web development. Specially after the release of IE9 with support for HTML5 and hardware-accelerated text, video and graphics speed up performance that makes websites perform like programs installed on your computer, or in the words of Dean Hachamovitch a “native experience”. And with announcement of IE10 Platform Preview 1 available for download, at MIX11, it is the first step in delivering the next wave of progress in native HTML5 support. So let’s get started and explore the most powerful element of HTML5 the <canvas> element.


HTML5 specifications defines the <canvas> element as “a resolution-dependent bitmap canvas which can be used for rendering graphs, game graphics, or other visual images on the fly.” A canvas is a rectangle in your page where you can use JavaScript to draw anything you want. By default a <canvas> element has no content and no border of its own. You can define a simple <canvas> element with this minimal HTML.
<canvas id="mycanvas" width="300" height="225"></canvas>
Here height and width specify the size of canvas and id is specified to get access to it in your JavaScript code. And anything you put between tags will be treated as fallback content if <canvas> element is not supported by the browser.
Apart from these attributes it also support two functions specific to this element, getContext and toDataURL


This function is the gateway to all things you can draw on <canvas>. Every canvas has a drawing context, which is where all the fun stuff happens. Once you’ve found a <canvas> element in the DOM (by using document.getElementById() or any other method you like), you call its getContext() method. Currently only "2d" context is supported, according to WHATWG Wiki CanvasContexts page there is also a "webgl" context but it’s not yet supported by many browsers, though it might be supported in future revision of specifications. So to get context you will pass a string "2d" as argument which will return a new CanvasRenderingContext2D Object, whose methods can be used to draw on <canvas>.


This method, when called with no arguments, return a data: URL (rfc2397) containing a representation of the anything thing on <canvas> as a PNG image file. You can also pass a string representation of any valid MIME Type to this function to get data in that format, like "image/png", "image/jpeg".

Canvas Drawing Model

Imagine you’re drawing a picture in ink. You don’t want to just dive in and start drawing with ink, because you might make a mistake. Instead, you sketch the lines and curves with a pencil, and once you’re happy with it, you trace over your sketch in ink.
Each canvas has a path. Defining the path is like drawing with a pencil. You can draw whatever you like, but it won’t be part of the finished product until you pick up the quill and trace over your path in ink.
In canvas almost all drawing method you call will add a path (except fillRect() and fillText() methods which paints a filled shape instantly), and will not draw until you call stroke(), fill() or clip() method. fill() method fills the path with current fillStyle(), stroke() method draws the path with current strokeStyle()s and clip() method creates a clipping region for the path.


Now let's explore how to use <canvas> element, and start drawing on canvas with its methods. For this example we will draw some simple shapes by using some of the methods of Context object, (for all methods please see Methods and Properties).

Define a <canvas>

You define a <canvas> with following simple markup.
<canvas id="mycanvas" width="300" height="100" style="border:1px solid black"></canvas>

Above is the simple <canvas>, i have given it a border so you can see it.

Get the Context

Next we'll get the drawing context by following lines of JavaScript.
var canvas = document.getElementById("mycanvas");
var context = canvas.getContext("2d");

Lets Draw on <canvas> !!!

We'll draw a square, a circle and some text on the <canvas>, for this we'll use following methods: (for all methods please see Methods and Properties)
  • fillRect( x, y, fWidth, fHeight):Paints a rectangle onto a CanvasRenderingContext2D object by using the current fill style.
  • beginPath():Resets the current path.
  • arc( x, y, radius, startAngle, endAngle, bAnticlockwise):Adds points to a path that represents an arc. (Angles are in radians).
  • fill():Fills sub-paths by using the current fill style.
  • fillText( text, x, y [, maxWidth]):Renders filled text to the canvas by using the current fill style and font. (maxWidth is optional it specifies the maximum possible text width. If the value is less than the width property, the text is scaled to fit.)
  • fillStyle:It is a property which sets the style that will be used to fill the shapes. it can be a CanvasGradient, a CSS color, or a CanvasPattern.
By using above methods we can write following JavaScript code to draw on <canvas>.
var acDegToRad = function(deg){ return deg * -(Math.PI/180)}
context.fillStyle = "rgb(0,160,250)"; 
context.arc(200,35,25, acDegToRad(0), acDegToRad(360)); /
context.fillText("Hi, I’m Samaj Shekhar", 100,80); 
Let me explain it line by line, in second line we set the fillStyle property with an rgb() string for blue color. Then we draw a filled rectangle at (10,10) (x,y) cordinates with 50px width and height, thereby making it a square. In fourth line we start a Path to create a circle, then in next line we define the circle with the arc() function, passing it the coordinates of (200,35)(x,y) for center of circle, a radius of 25px, then a starting angle of 0deg and ending angle of 360deg, thereby completing a full path of circle. Since this function takes angles in "Radians" and by default draws angle in clockwise direction, I have defined a small function on first line, acDegToRad() which converts passed value in degrees to radians then negates the result to make degrees anticlockwise (as we were taught to do in schools :). Then in sixth line we call the fill() method to actually paint and fill the path, which is a circle in this case. The last line simply draws the string at (100,80)(x,y) coordinates. By default the "font" of 2d context is 10px sans-serif. You can set any CSS font by passing it as string to context.font property
And here are the shapes that get drawn,

Below is another canvas with a fairly complex graphic for logo of PORTAL2, one of my favourite games :). In my next post we'll dive deeper in other functions of <canvas> and I'll give a walkthrough of how to draw this nice PORTAL2 logo.

Methods and properties

As of now CanvasRenderingContext2D Object contains only 49 methods and properties. MSDN has a nice list of them. Below is the short description of each :< /p>
canvasGets a back reference to the canvas object that the current context derives from.
fillStyleGets or sets the current style that is used to fill shapes.
fontGets or sets the current font for the context.
globalAlphaGets or sets the current alpha or transparency value that is applied to global composite rendering operations.
globalCompositeOperationGets or sets a value that indicates how source images are drawn onto a destination image.
lineCapGets or sets the current line cap style.
lineJoinGets or sets the type of corner that is created when two lines meet.
lineWidthGets or sets the current line width, in pixels.
miterLimitGets or sets the maximum allowed ratio between half of the lineWidth value and the miter length.
shadowBlurGets or sets the current level of blur that is applied to shadows.
shadowColorGets or sets the color to use for shadows.
shadowOffsetXGets or sets the horizontal distance of a shadow from a shape.
shadowOffsetYGets or sets the vertical distance of a shadow from a shape.
strokeStyleGets or sets the current style that is used for strokes of shapes.
textAlignGets or sets the current anchor point or alignment settings for text in the current context.
textBaselineGets or sets the current settings for the font baseline alignment.
arcAdds points to a path that represents an arc.
arcToDraws an arc of a fixed radius between two tangents that are defined by the current point in a path and two additional points.
beginPathResets the current path.
bezierCurveToAdds a point to the current sub-path by using the specified control points that represent a cubic Bézier curve.
clearRectClears the pixels on a CanvasRenderingContext2D object within a given rectangle.
clipSpecifies a new clipping region.
closePathCloses the current subpath and starts a new subpath that has a start point that is equal to the end of the closed subpath.
createImageDataReturns a CanvasImageData object that has dimensions in CSS pixels.
createLinearGradientCreates an object that represents a linear gradient to use in a canvas context.
createPatternReturns a CanvasPattern object that repeats the specified element in the specified direction.
createRadialGradientReturns an object that represents a radial or circular gradient to use in a canvas context.
drawImageDraws a specified image onto a canvas.
fillFills subpaths by using the current fill style.
fillRectPaints a rectangle onto a CanvasRenderingContext2D object by using the current fill style.
fillTextRenders filled text to the canvas by using the current fill style and font.
getImageDataReturns an ICanvasImageData object that represents the pixel data for the specified rectangle on a canvas.
isPointInPathDetermines if the specified point is in the current path.
lineToAdds a new point to a subpath and connects that point to the last point in the subpath by using a straight line.
measureTextReturns a CanvasTextMetrics object that contains the width of the specified text.
moveToCreates a new subpath by using the specified point.
putImageDataPaints the data from a specified CanvasImageData object onto a canvas.
quadraticCurveToAdds a point to the current subpath by using the specified control points that represent a quadratic Bézier curve.
rectCreates a new closed rectangular subpath.
restoreReturns previously saved CanvasRenderingContext2D path state and attributes.
rotateRotates the current context coordinates (that is, a transformation matrix).
saveSaves the state of the current context.
scaleScales the current context by the specified horizontal (x) and vertical (y) factors.
setTransformResets the current transformation matrix of the current context back to its default and then multiplies it by the specified matrix.
strokeRenders the strokes of the current subpath by using the current stroke styles.
strokeRectCreates an outline of the specified rectangle on a canvas by using the current stroke, line width, and join styles.
strokeTextRenders the specified text at the specified position by using the current font and strokeStyle property.
transformModifies the transformation matrix of the current context.
translateSpecifies values to move the origin point in a canvas.

No comments:

Post a Comment