<canvas>, is probably the most dramatic element to be added to HTML5. It allows graphics on the client’s browser to be dynamically updated.
HTML Representation
The <canvas> element has the following attributes:
Attribute |
Description |
height |
The height of the canvas, specified in pixels. Default is 150 |
id |
An identifier for the canvas so that it is accessible via Javascript |
width |
The width of the canvas, specified in pixels. Default is 300 |
JavaScript API
All dynamic behavior for the canvas is specified in JavaScript. Once you have access to the canvas element, you must create a context in which the canvas can be drawn on.
The following code snippet shows how to access the Canvas and retrieve its graphical context.
var canvas = document.getElementById(“documentCanvas”);
var context = canvas.getContext(“2d”);
Currently the only valid context for the Canvas element is 2D. There will probably be a 3D context in the future. The Context object has the a number of different methods. These include transformations, compositing, state, coloring and shape methods.
Transformations
When creating shapes and paths, transformations are applied to coordinates. Transformations must be performed in reverse order.
Transformation Methods |
context.rotate(angle) Changes the transformation matrix to apply a clockwise rotation expressed in radians |
context.scale(x,y) Applies a scaling transformation, where x represents scale factor in the horizontal direction and y represents the scale factor in the vertical direction, specified in multiples |
context.setTransform(m11, m12, m21, m22, dx, dy) Resets the current transformation matrix to the identity matrix, then the given transformation matrix is applied. |
context.tranform(m11, m12, m21, m22, dx, dy) Transforms the context by multiplying the current transformation matrix with the matrix described by m11 m21 dx m21 m22 dy 0 0 0 |
context.translate(x,y) Applies a translation transformation to the context where x is the distance along the horizontal and y is the distance along the vertical, specified in coordinate space units |
Context State
A context has a stack of drawing states including:
- The current transformation matrix
- The current clipping region
- Values for a number of attributes
The following methods can be used to manage state:
Context State Methods |
context.restore() Pops the top state on the stack and acts as an undo action and restores the context to that state |
context.save() Pushes the current state onto the stack |
Compositing
All drawing operations are affected by the global compositing values.
Compositing Methods |
context.globalAlpha [ = value] Returns or sets the current alpha value applied to rendering operations. Values outside the range 0.0 (fully transparent) to 1.0 (no transparency) are ignored. |
context.globalCompositeOperation [=value] Returns or sets the current composition operation from the list below:
- copy Display source image instead of destination image
- destination-atop Display destination image wherever both are opaque. Display source image where source is opaque but destination is transparent
- destination-in Display destination image wherever both destination and source images are opaque
- destination-outDisplay destination image wherever destination image is opaque and source image is transparent
- destination-overDisplay destination image wherever destination image is opaque. Source image elsewhere
- lighter Display the sum of source and destination images
- source-atop Display source image wherever both images are opaque. Display destination image where destination is opaque but source is transparent
- source-in Display source image wherever both source image and destination image are opaque
- source-out Display source image wherever source image is opaque and destination image is transparent
- source-over (default) Display source image wherever source image is opaque. Destination image elsewhere
- vendorName-operationName Vendor specific operations follow this format
- xor Exclusive OR of source and destination image
|
Colors and Styles
Style Methods |
context.fillStyle[=value] Returns or sets the current style used for filling shapes. Can be a string containing a CSS color, or a CanvasGradient /CanvasPattern |
context.strokeStyle[=value] Returns or sets the current style used for the stroke of shapes. Can be a string containing a CSS color, or a CanvasGradient /CanvasPattern |
To create the appropriate CanvasGradient object use either the createLinearGradient() or createRadialGradient() from the Context object. The resulting CanvasGradient object has the following method available:
CanvasGradient Methods |
gradient.addColorStop(offset, color) Adds a new stop to the gradient at a point between 0.0 and 1.0, each representing each end of the gradient. The color parameter must be a CSS color |
To create a CanvasPattern object use the following method:
CanvasPattern Method |
context.createPattern(image, repetition) Creates a new CanvasPattern object using the given image.The image is repeated in one of these specified directions:
- repeat: both directions
- repeat-x: horizontal only
- repeat-y: vertical only
- no-repeat: neither
The image can be either an img, video or canvas. |
Line Styles
The following line styles can be applied from the context:
Line Style Methods |
context.lineCap[=value] The ending that will be placed at the end of the line. Either butt, round or square. Initially set to butt |
context.lineJoin[=value] The corners that will be placed where two lines meet. Either bevel, round or miter. Initially set to miter |
context.lineWidth[=value] Width of the line, in coordinate space units. Initially set to 1.0 |
context.miterLimit[=value] Maximum allowed ratio of the miter length to half the line width. Miter length is the distance from the point where the join occurs to the intersection of the line edges on the outside of the join. Initially set to 10.0. |
Shadows
There are four global shadow attributes that affect all drawing operations:
Shadow Methods |
context.shadowBlur[=value] The size of the blurring effect, initially set to 0. |
context.shadowColor[=value] The color of the shadow, initially transparent black. Specified as a CSS color. |
context.shadowOffsetX[=value] context.shadowOffsetY[=value] The distance that a shadow will be offset in horizontal and vertical distance |
Shapes
Three methods are available to create simple shapes, or rectangles:
Simple Shape Methods |
context.clearRect(x,y,w,h) Clears the pixels in the specified rectangle that also intersect the current clipping region to fully transparent black, erasing the previous image |
context.fillRect(x,y,w,h) Paints the specified rectangle using the defined fillStyle |
context.strokeRect(x,y,w,h) Draws the outline of the rectangle path using strokeStyle, lineWidth, lineJoin and miterLimit attributes |
The context always has a current path, which can have zero or more sub-paths. These are used to create complex shapes.
Complex Shape Methods |
context.arc(x,y,radius, startAngle, endAngle, anticlockwise) Creates an arc described by the circumference of the circle in the arguments, in the given direction |
context.arcTo(x1,y1,x2,y2,radius) Adds a point to the path that is connected to the previous point by an arc |
context.beginPath() Resets the current path |
context.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y) Adds a point to the path that is connected to the previous point by a cubic Bezier curve |
context.clip() Constrains the clipping region to a given path |
context.closePath() Marks the current subpath as closed, and starts a new subpath |
context.fill() Fills the subpaths with the current fill style |
context.lineTo(x,y) Adds a point to the current subpath that is connected to the previous point by a line |
context.moveTo(x,y) Creates a new subpath with the given point as its first and only point |
context.quadrativeCurveTo(cpx,cpy,x,y) Adds a point to the current path that is connected to the previous one by a quadratic Bezier curve |
context.rect(x,y,w,h) Adds a new closed subpath to the path, representing the given rectangle |
context.stroke() Creates the strokes of the subpaths with the current stroke style |
context.isPointInPath(x,y) Returns true if the given point is in the current path |
Text
The following attributes and operations are available for manipulating text:
Text Methods |
context.font[=value] Returns or sets the current font setting in the CSS font property syntax |
context.textAlign[=value] Returns or sets the current text alignment settings. Acceptable values are start (default), end, left, right or center |
context.textBaseline[=value] Returns or sets the current baseline alignment settings. Can be one of top, middle, hanging, alphabetic (default), ideographic or bottom |
context.fillText(text,x,y,maxWidth) Renders fill for given text at a given position. Text is scaled to fit maxWidth if provided |
context.strokeText(text, x, y, maxWidth) Renders stroke for given text at a given position. Text is scaled to fit maxWidth if provided |
metrics = context.measureText(text) Returns a TextMetrics object with the metrics of the given text in the current font |
metrics.width Returns the advance width of the text that was passed to the measureText() method |
Images
There are three image functions available to draw an image on the Canvas:
Image Methods |
context . drawImage(image, dx, dy) context . drawImage(image, dx, dy, dw, dh) context . drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) Draws the given image onto the Canvas. The image attribute must be one of <img>, canvas or <video> |
In order to manipulate pixels, you must first create an ImageData object using one of the following methods:
ImageData Creation Methods |
context.createImageData(sw,sh) Returns an ImageData object with the given dimensions in CSS pixels |
context.createImageData(imagedata) Returns an ImageData object with the same dimensions as the imagedata parameter |
context.getImageData(sx,sy,sw,sh) Returns an ImageData object containing the image data for the given rectangle of the canvas |
The ImageData object has the following properties:
ImageData Properties |
imagedata.data A one dimensional array containing the data for the ImageData object (as a CanvasPixelArray) |
imagedata.height imagedata.width Actual dimensions of the data in the ImageData object |
The following method is used when you want to utilize the ImageData object:
ImageData Methods |
context.putImageData(imagedata, dx, dy, dirtyX, dirty, dirtyWidth, dirtyHeight) Paints the data of the given ImageData object onto the Canvas |
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}