Important: The information in this document is obsolete and should not be used for new development.
Safari, Dashboard, and any Web Kit–based application can do arbitrary drawing of content using the canvas tag—a Web Kit extension introduced in Mac OS X version 10.4. This extension lets you reserve an area of your web page or widget and use rendering calls like those found in Quartz to paint complex paths and shapes in that area.
The canvas tag is an HTML extension that you include in your HTML page to specify where you want drawing to occur. The canvas tag supports the same attributes as the <img> tag with the exception of the src attribute, which is ignored. You can specify any of the other attributes you would normally specify for an image. At a minimum, you must specify the attributes listed in Table 1-1.
Attribute |
Description |
|---|---|
|
Specifies the height of the canvas. You can specify this value in the same way you specify the height of an image, either as a fixed number of pixels or a percentage of the window height. |
|
Specifies the canvas object identifier. This value must be unique within a given HTML page. |
|
Specifies the width of the canvas. You can specify this value in the same way you specify the height of an image, either as a fixed number of pixels or a percentage of the window height. |
You can place the canvas tag anywhere in your HTML page. You may also include more than one canvas in your web page or widget as long as the id attribute of each is unique. For example, to define a canvas, you could use code similar to the following body in your HTML page:
<body> |
<canvas id="MyCanvas" width='100' height='100' style="position:absolute; left:0px; top:0px; z-index:1"/> |
</body> |
Each canvas object on a web page is intricately linked to a special JavaScript object called a 2D context object. This object manages the graphics state information for the canvas and exposes a set of methods that you can call from your JavaScript code to draw onto the canvas.
To obtain an instance of the 2D context object for a particular canvas, you must call the getContext method of the canvas object, passing the string "2d" as a parameter. The following example shows part of a JavaScript function to handle the drawing for a canvas. The function uses the Document Object Model (DOM) to obtain the canvas object and then calls the getContext method to get the 2D context object for the canvas.
function MyJavaScriptFunction() |
{ |
var canvas = document.getElementById("MyCanvas"); |
var context = canvas.getContext("2d"); |
// Draw content here... |
} |
In this example, the body of the web page would have to include a canvas tag whose id attribute was set to "MyCanvas". If your web page contained multiple canvases, you would need to acquire a separate 2D context object for each one.
When you want to draw a shape, you set the current path to that shape and then paint the shape by stroking, filling, or both stroking and filling. Stroking is the process of painting a line along the current path. Filling is the process of painting the area contained within the path.
You use paths to draw both simple shapes (for example, lines, circles, or rectangles) and complex shapes (such as the silhouette of a mountain range) in a canvas. You can use a path to both draw the outline of a shape and fill the inside of a shape.
The basic steps in building a path are as follows:
Start building the path by opening a new path with beginPath.
Define the starting point of the new subpath using the moveTo method.
Add one or more segments to the subpath using such methods as lineTo and quadraticCurveTo.
Repeat steps 2 and/or 3 until the path is defined.
Optionally, call closePath to connect the path’s start and end points with a straight line.
Prior to building the path, you can define properties such asfillStyle or strokeStyle that can be used by drawing primitives to fill or stroke the path.
When you close the path, the canvas connects the end of the last line segment to the start of the first segment and terminates the current subpath. If you don’t close the path by calling closePath before painting, the path is implicitly closed for you by drawing primitives that fill or clip (but it is not closed for stroking).
Table 1-2 lists all the editable and readable properties of a Canvas object.
Property |
Description |
|---|---|
|
The color or style the canvas applies when filling paths. When you set this property, the canvas sets the fill style parameter of the graphics state. If you intend for the fill style to be a color, you can set it in several different ways depending on the color space you intend to use. For web-safe colors, pass a web color specification string of the form If you want the shape fill to have an alpha, use the CSS You can also set the fill style to be a gradient or pattern. Use the |
|
A float value indicating the alpha channel value, which determines the opacity of content drawn on the canvas. The range of values is between 0.0 (fully transparent) and 1.0 (no additional transparency). By default, this parameter’s value is 1.0. IThe canvas uses the alpha value in the current graphics state to determine how to composite newly painted objects. |
|
Determines how the canvas is displayed relative to any background content. The string identifies the desired compositing mode. If you do not set this value explicitly, the canvas uses the Table 1-2 lists the valid compositing operators. When used with this property, the source image refers to the canvas and the destination image refers to the web view. |
|
A string value that determines the end style used when drawing a line. Specify the string |
|
A string value that determines the join style between lines. Specify the string |
|
A float value indicating the line width for drawing operations. This value must be greater than 0. You can affect the width of lines and curves that the canvas draws by modifying the line width property of the graphics state. The line width is the total width of the line, expressed in units of the user space. The line surrounds the center of the path, with half of the total width on either side. |
|
A float value with the new miter limit. You use this property to specify how the canvas draws the juncture between connected line segments. If the line join is set to |
|
Defines the width, in coordinate space units, that a shadow should cover. If you do not set this value explicitly, the canvas uses a value of 0. Any attempts to set this property to a negative value are ignored. |
|
The color the canvas applies when displaying a shadow. When you set this property, the canvas sets the shadow color parameter of the graphics state.. You can set the shadow color in several different ways depending on whether or not you want to use opacity. For opaque, web-safe colors, pass a web color specification string of the form If you want the shadow color to have an alpha, use the CSS |
|
Defines the distance, in coordinate space units, that a shadow should be offset in the positive horizontal direction. If you do not set this value explicitly, the canvas uses a value of 0. |
|
Defines the distance, in coordinate space units, that a shadow should be offset in the positive vertical direction. If you do not set this value explicitly, the canvas uses a value of 0. |
|
The color or style the canvas applies when stroking paths. When you set this property, the canvas sets the stroke style parameter of the graphics state. If you intend for the stroke style to be a color, you can set it in several different ways depending on the color space you intend to use. For web-safe colors, pass a web color specification string of the form If you want the shape stroke to have an alpha, use the CSS You can also set the stroke style to be a gradient or pattern. Use the |
Table 1-2 describes the operators supported by the context.globalCompositeOperation property. Use these to define the compositing operators for the canvas object.
Operator |
Description |
|---|---|
|
Displays the source image instead of the destination image. |
|
Display the sum of the source image and destination image, with color values approaching 0 as a limit. |
|
Display the destination image wherever both images are opaque. Display the source image wherever the source image is opaque but the destination image is transparent. |
|
Display the destination image wherever both the destination image and source image are opaque. Display transparency elsewhere. |
|
Display the destination image wherever the destination image is opaque and the source image is transparent. Display transparency elsewhere. |
|
Display the destination image wherever the destination image is opaque. Display the source image elsewhere. |
|
Display the sum of the source image and destination image, with color values approaching 1 as a limit. |
|
Display the source image wherever both images are opaque. Display the destination image wherever the destination image is opaque but the source image is transparent. Display transparency elsewhere. |
|
Display the source image wherever both the source image and destination image are opaque. Display transparency elsewhere. |
|
Display the source image wherever the source image is opaque and the destination image is transparent. Display transparency elsewhere. |
|
Display the source image wherever the source image is opaque. Display the destination image elsewhere. |
|
Exclusive OR of the source and destination images. Works only with black and white images and is not recommended for color images. |
(context.createLinearGradient(x0, y0, x1, y1)).addColorStop(offset, color)
Adds a color at an offset point to a gradient.
(context.createRadialGradient(x0, y0, r0, x1, y1, r1)).addColorStop(offset, color)
The offset is a float value between 0.0 and 1.0, and is defined within the context of the gradient type. Any values less than 0 or greater than 1 is ignored.
Adds an arc of a circle to the current subpath.
context.arc(x, y, radius, startAngle, endAngle, clockwise)
The arc is built based on the circle whose origin and radius are specified by the x, y, and radius parameters. The startAngle parameter specifies the angle of the starting point of the arc, measured in radians from the positive x-axis. The endAngle parameter specifies the angle of the endpoint of the arc, measured in radians from the positive x-axis. Specify 1 for the clockwise parameter to draw the arc in a clockwise direction; otherwise, specify 0.
If the current path already contains a subpath, the canvas appends a straight line segment from the current point to the starting point of the arc. If the current path is empty, the canvas creates a new subpath for the arc and does not add an initial line segment. After adding the arc, the current point is set to the endpoint of the arc.
Adds an arc of a circle to the current subpath, using a radius and tangent points.
context.arcTo(x1, y1, x2, y2, radius)
This method draws an arc that is tangent to the line from the current point to (x1, y1) and to the line from (x1, y1) to (x2, y2). The start and end points of the arc are located on the first and second tangent lines, respectively. The start and end points of the arc are also the “tangent points” of the lines.
If the current point and the first tangent point of the arc (the starting point) are not equal, the canvas appends a straight line segment from the current point to the first tangent point. After adding the arc, the current point is reset to the endpoint of the arc (the second tangent point).
Creates a new empty path in the canvas.
context.beginPath()
You use paths to draw both simple shapes (for example, lines, circles, or rectangles) and complex shapes (such as the silhouette of a mountain range) in a canvas. You can use a path to both draw the outline of a shape and fill the inside of a shape.
Before painting a shape, you must create the shape to be painted using the current path. You build a path from a set of subpaths, each of which is a list of one or more segments, either straight lines or curves.
A canvas can have only a single path in use at any time. Therefore, if the specified context already contains a current path when you call this method, the canvas replaces the previous current path with the new path. In this case, the canvas discards the old path and any data associated with it.
Note: The current path is not part of the graphics state. Consequently, saving and restoring the graphics state has no effect on the current path.
Appends a cubic Bézier curve to the current path.
context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
A cubic curve segment has a start point, two control points, and an endpoint. The start point is the current endpoint of the open path. The cp1x, cp1y, cp2x, and cp2y parameters specify the two control points for the path. The x and y parameters specify the new endpoint for the path. After adding the segment, the current point is reset from the beginning of the new segment to the endpoint of that segment.
Paints a transparent rectangle.
context.clearRect(x, y, width, height)
When you call this method, the canvas effectively “erases” the contents of the specified rectangle. The parameters of this method all contain float values.
Sets the current clipping path, using the nonzero winding number rule.
context.clip()
This method uses the nonzero winding number rule to calculate the intersection of the current path with the current clipping path. The canvas then uses the path resulting from the intersection as the new current clipping path for subsequent painting operations.
Unlike the current path, the current clipping path is part of the graphics state. Therefore, to re-enlarge the paintable area by restoring the clipping path to a prior state, you must save the graphics state before you clip and restore the graphics state after you’ve completed any clipped drawing.
After determining the new clipping path, the method resets the current path to an empty path.
Closes and terminates an open subpath.
context.closePath()
When a subpath is open and you call this method, the canvas closes the subpath (draws a straight line that connects the current point to the starting point), and terminates the subpath (the current point is no longer defined).
If no subpath is open, calling this method does nothing.
Note: You can stroke along an open subpath. When a subpath is open and you fill or clip, however, the canvas implicitly closes the subpath for you.
Returns a gradient object representing a linear gradient.
context.createLinearGradient(x0, y0, x1, y1)
This method takes in two coordinates, (x0, y0) and (x1, y1), and returns an object that represents a gradient between them.
Use addColorStop() to add colors and offsets to a gradient. The 0 offset in this case is the start of the gradient (x0, y0) while the 1 offset is the end of the gradient (x1, y1).
The returned object can be assigned to the fillStyle and strokeStyle properties or used in comparisons with them.
Returns a pattern object representing a repeating pattern.
context.createPattern(image, repetition)
This method takes an image and a repetition style and produces a pattern style that you can use when filling in your shapes. The repetition parameter accepts a string as its value:
Value |
Description |
|---|---|
|
Repeat the image in both the x and y directions. |
|
Repeat the image in the x direction. |
|
Repeat the image in the y direction. |
|
Do not repeat the image beyond showing it once. |
The returned object can be assigned to the fillStyle and strokeStyle properties or used in comparisons with them.
Returns a gradient object representing a radial gradient.
context.createRadialGradient(x0, y0, r0, x1, y1, r1)
This method takes in two coordinates, (x0, y0) and (x1, y0) and corresponding radii. It creates two circles using the coordinates and the radii provided and returns an object that has a gradient between the edges of the circles.
Use addColorStop() to add colors and offsets to a gradient. The 0 offset in this case is the circumference of the first circle (x0, y0, r0) while the 1 offset is the circumference of the second circle (x1, y1, r1).
The returned object can be assigned to the fillStyle and strokeStyle properties or used in comparisons with them.
context.drawImage(image, x, y)
context.drawImage(image, x, y, width, height)
Draws an image in the specified rectangle.
context.drawImage(image, sx, sy, swidth, sheight, dx, dy, dwidth, dheight)
This method is overloaded with three variants, used to draw the contents of a JavaScript Image object into the context.
The first of these, drawImage(image,
x, y), draws the image at the x and y coordinates within the context. The image is sized as it is in the object.
The second method, drawImage(image, x, y, width,
height), is where x, y, width, and height parameters contain values representing the bounding rectangle for the image. These values are specified in the coordinate system of the canvas. If the specified coordinates lie outside the canvas bounds, the image will be clipped.
The third method, context.drawImage(image, sx,
sy, swidth, sheight, dx, dy, dwidth, dheight), draws the portion of the image specified by the source rectangle (sx, sy, swidth, and sheight) onto the canvas at the specified destination rectangle (dx, dy, dwidth, dheight). The source rectangle is specified in the image coordinate space and the destination rectangle is specified in the canvas coordinate space. The image parameter must contain a valid <image>, <canvas>, or JavaScript Image object.
This method has been depreciated. See drawImage for more information.
Paints the area within the current path, using the nonzero winding-number fill rule.
context.fill()
The fill color is an attribute of the graphics state. You can set the current fill color by setting a value for the fillStyle property.
When you fill the current path, the canvas fills each subpath independently. Any subpath that has not been explicitly closed is closed implicitly by the fill routines.
The fill rule used by this method is called the nonzero winding number rule. To understand how this rule works, draw a line in any direction, starting from the given point and moving to infinity. Starting with a count of zero, add one to the count every time a path segment crosses the line from left to right, and subtract one every time a path segment crosses the line from right to left. If the result is zero, the point is outside the path and is not filled.
Paints the area within the specified rectangle.
context.fillRect(x, y, width, height)
This method uses the current fill color to paint the area of the specified rectangle. The parameters of this method all contain float values.
As a side effect of calling this method, the canvas clears the current path.
Appends a straight line segment from the current point to the point you specify.
context.lineTo(x, y)
You can use straight line segments, cubic and quadratic Bézier curve segments, and rectangles to specify a path. You can append a single straight line segment to the current subpath using this method. After adding the line segment, the current point is reset from the beginning of the new line segment to the endpoint of that line segment, as specified by the x and y parameters.
Begins a new subpath at the point you specify.
context.moveTo(x, y)
Before painting a shape in the canvas, you must create the shape to be painted using the current path. You build a path from a set of subpaths, each of which is a list of one or more segments, either straight lines or curves.
This method begins a new subpath starting at the point you specify with the x and y parameters. This point is defined to be the “current” point, and it defines the starting point of the next line segment. The canvas sets the current point in one of two ways:
Explicitly, when you call this method to begin a new subpath at a given point
Implicitly, when you add a new curve or straight line segment to the subpath; after adding the segment, the current point is reset from the beginning of the new segment to the endpoint of that segment
Appends a quadratic Bézier curve to the current path.
context.quadraticCurveTo(cpx, cpy, x, y)
A quadratic curve segment has a start point, one control point, and an endpoint. The start point is the current point of the canvas. The cpx and cpy parameters specify the control point. The x and y parameters specify the new endpoint. After adding the segment, the current point is reset from the beginning of the new segment to the endpoint of that segment.
Adds a new subpath, consisting of a single rectangle, to the canvas.
context.rect(x, y, width, height)
The parameters for this method all contain float values.
Restores the current graphics state to the state most recently saved.
context.restore()
If you wish to save the settings of the current drawing environment, that is, the current graphics state, you can call the save method. When you call save, the canvas saves the current graphics state to the top of the graphics state stack.
To restore your drawing environment to a previously saved state, you can use this method. When you call restore, the canvas removes the most recently saved graphics state from the top of the stack and uses that state’s saved settings for the current graphics state.
Rotates the user coordinate system of the canvas.
context.rotate(angle)
The angle parameter specifies the amount of coordinate-space rotation and is measured in radians.
The current transformation matrix (CTM) specifies the mapping from device-independent user space coordinates to a device space. By modifying the current transformation matrix, you can modify (scale, translate, rotate) the objects you draw. It’s important to note the order of events necessary to transform an object in a graphics context. Prior to drawing the object, you must first transform the coordinate space of the context (by calling this method), and then draw the object.
For example, to rotate an image, you must call this method to rotate the coordinate space of the context before drawing the image. When you draw the image, the canvas draws to the window using the rotated coordinate system. You specify both the magnitude and direction of the rotation by specifying an angle of adjustment in radians.
To restore the previous coordinate space, you must save the graphics state before modifying the CTM, and restore the graphics state after drawing.
Saves a copy of the current graphics state.
context.save()
The graphics state contains data describing the current drawing environment. Methods that draw to the canvas use the graphics state settings to determine how to render their results.
Each canvas maintains a stack of graphics states. If you wish to save the settings of the current drawing environment, that is, the current graphics state, you can call the save method. When you call save, the canvas object saves the current graphics state to the top of the graphics state stack.
To restore your drawing environment to a previously saved state, you can use the restore method. When you call restore, the canvas removes the most recently saved graphics state from the top of the stack and uses that state’s saved settings for the current graphics state.
For example, you could use the following set of steps to paint a blue shape, then a green shape, then a blue shape, by saving and restoring the graphics state.
Modify the graphics state by changing the fill color to blue.
Save the graphics state.
Fill a shape—the shape is painted with blue.
Set the fill color to green.
Fill a shape—the shape is painted with green.
Restore the graphics state.
Fill a shape—because the graphics state has been restored to the state at the time it was previously saved, the shape is painted blue.
Note that not all aspects of the current drawing environment are elements of the graphics state. For example, the current path is not considered part of the graphics state and is therefore not saved when you call this method.
The graphics state parameters that are saved when you call this method include the following:
The CTM (current transformation matrix)
The clip region
The line width
The line join
The miter limit
The line cap
The flatness
The fill color
The stroke color
The alpha value
The shadow parameters
Changes the scale of the canvas coordinate system.
context.scale(sx, sy)
The sx parameter contains a float value with the x-axis scale factor. The sy parameter contains a float value with the y-axis scale factor.
The current transformation matrix (CTM) specifies the mapping from device-independent user space coordinates to a device space. By modifying the current transformation matrix, you can modify (scale, translate, rotate, skew) the objects you draw. It is important to note the order of events necessary to transform an object in a graphics context. Prior to drawing the object, you must first transform the coordinate space of the context (by calling this method), and then draw the object.
Scaling operations modify the x- and y-coordinates by a given scaling factor. The magnitude of the x and y factors governs whether the new coordinates are larger or smaller than the original. For example, specifying the value 2.0 for the sx parameter causes subsequently drawn objects to appear at twice their specified width. In addition, by making the x factor negative, you can flip the coordinates about the y-axis; similarly, you can flip coordinates about the x-axis by making the y factor negative.
To restore the previous coordinate space, you must save the graphics state before modifying the CTM, and restore the graphics state after drawing.
Paints a line along the current path.
context.stroke()
To modify the behavior of this method, you can change any of the following graphics state properties:
The line width
The line join
The line cap
The miter limit
The line dash pattern
The stroke color space
The stroke color
Paints an outline of a rectangle.
context.strokeRect(x, y, width, height)
This method uses the current stroke color to paint the path represented by the specified rectangle. The parameters of this method all contain float values.
To alter the appearance of the painted outline, you can modify the following attributes of the graphics state:
The line width
The line join
The miter limit
The line dash pattern
The stroke color space
The stroke color
Changes the origin of the canvas coordinate system.
context.translate(tx, ty)
The tx parameter contains a float value with the x-axis translation value. The ty parameter contains a float value with the y-axis translation value.
The current transformation matrix (CTM) specifies the mapping from device-independent user space coordinates to a device space. By modifying the current transformation matrix, you can modify (scale, translate, rotate) the objects you draw. It’s important to note the order of events necessary to transform an object in a graphics context. Prior to drawing the object, you must first transform the coordinate space of the page (by calling this method), and then draw the object.
This method displaces the x- and y-axes (thus, the origin) of the coordinate system by the values you specify. When you draw into this adjusted coordinate space, the x- and y-coordinates of your drawing are also displaced.
To restore the previous coordinate space, you must save the graphics state before modifying the CTM, and restore the graphics state after drawing.
Last updated: 2005-10-04