<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.Introduction
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
getContext()
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>
.getDataURL()
This method, when called with no arguments, return adata: 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.Example
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.
<canvas>
.var acDegToRad = function(deg){ return deg * -(Math.PI/180)} context.fillStyle = "rgb(0,160,250)"; context.fillRect(10,10,50,50); context.beginPath(); context.arc(200,35,25, acDegToRad(0), acDegToRad(360)); / context.fill(); 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
propertyAnd 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 nowCanvasRenderingContext2D
Object contains only 49 methods and properties. MSDN has a nice list of them. Below is the short description of each :< /p>
Property | Description |
---|---|
canvas | Gets a back reference to the canvas object that the current context derives from. |
fillStyle | Gets or sets the current style that is used to fill shapes. |
font | Gets or sets the current font for the context. |
globalAlpha | Gets or sets the current alpha or transparency value that is applied to global composite rendering operations. |
globalCompositeOperation | Gets or sets a value that indicates how source images are drawn onto a destination image. |
lineCap | Gets or sets the current line cap style. |
lineJoin | Gets or sets the type of corner that is created when two lines meet. |
lineWidth | Gets or sets the current line width, in pixels. |
miterLimit | Gets or sets the maximum allowed ratio between half of the lineWidth value and the miter length. |
shadowBlur | Gets or sets the current level of blur that is applied to shadows. |
shadowColor | Gets or sets the color to use for shadows. |
shadowOffsetX | Gets or sets the horizontal distance of a shadow from a shape. |
shadowOffsetY | Gets or sets the vertical distance of a shadow from a shape. |
strokeStyle | Gets or sets the current style that is used for strokes of shapes. |
textAlign | Gets or sets the current anchor point or alignment settings for text in the current context. |
textBaseline | Gets or sets the current settings for the font baseline alignment. |
Method | Description |
---|---|
arc | Adds points to a path that represents an arc. |
arcTo | Draws an arc of a fixed radius between two tangents that are defined by the current point in a path and two additional points. |
beginPath | Resets the current path. |
bezierCurveTo | Adds a point to the current sub-path by using the specified control points that represent a cubic Bézier curve. |
clearRect | Clears the pixels on a CanvasRenderingContext2D object within a given rectangle. |
clip | Specifies a new clipping region. |
closePath | Closes the current subpath and starts a new subpath that has a start point that is equal to the end of the closed subpath. |
createImageData | Returns a CanvasImageData object that has dimensions in CSS pixels. |
createLinearGradient | Creates an object that represents a linear gradient to use in a canvas context. |
createPattern | Returns a CanvasPattern object that repeats the specified element in the specified direction. |
createRadialGradient | Returns an object that represents a radial or circular gradient to use in a canvas context. |
drawImage | Draws a specified image onto a canvas. |
fill | Fills subpaths by using the current fill style. |
fillRect | Paints a rectangle onto a CanvasRenderingContext2D object by using the current fill style. |
fillText | Renders filled text to the canvas by using the current fill style and font. |
getImageData | Returns an ICanvasImageData object that represents the pixel data for the specified rectangle on a canvas. |
isPointInPath | Determines if the specified point is in the current path. |
lineTo | Adds a new point to a subpath and connects that point to the last point in the subpath by using a straight line. |
measureText | Returns a CanvasTextMetrics object that contains the width of the specified text. |
moveTo | Creates a new subpath by using the specified point. |
putImageData | Paints the data from a specified CanvasImageData object onto a canvas. |
quadraticCurveTo | Adds a point to the current subpath by using the specified control points that represent a quadratic Bézier curve. |
rect | Creates a new closed rectangular subpath. |
restore | Returns previously saved CanvasRenderingContext2D path state and attributes. |
rotate | Rotates the current context coordinates (that is, a transformation matrix). |
save | Saves the state of the current context. |
scale | Scales the current context by the specified horizontal (x) and vertical (y) factors. |
setTransform | Resets the current transformation matrix of the current context back to its default and then multiplies it by the specified matrix. |
stroke | Renders the strokes of the current subpath by using the current stroke styles. |
strokeRect | Creates an outline of the specified rectangle on a canvas by using the current stroke, line width, and join styles. |
strokeText | Renders the specified text at the specified position by using the current font and strokeStyle property. |
transform | Modifies the transformation matrix of the current context. |
translate | Specifies values to move the origin point in a canvas. |