Apple Developer Connection
Member Login Log In | Not a Member? Contact ADC

Next Page > Hide TOC

Legacy Documentclose button

Important: The information in this document is obsolete and should not be used for new development.

Canvas

Overview

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.

Defining the Canvas Space

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.

Table 1-1  Required attributes of <canvas> tag

Attribute

Description

height

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.

id

Specifies the canvas object identifier. This value must be unique within a given HTML page.

width

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>

Getting a Graphics Context for a Canvas

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.

Creating Shapes

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:

  1. Start building the path by opening a new path with beginPath.

  2. Define the starting point of the new subpath using the moveTo method.

  3. Add one or more segments to the subpath using such methods as lineTo and quadraticCurveTo.

  4. Repeat steps 2 and/or 3 until the path is defined.

  5. 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).

Canvas Properties

Table 1-2 lists all the editable and readable properties of a Canvas object.

Property

Description

context.fillStyle

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 "#RRGGBB", which represents an RGB color using hexidecimal numbers.

If you want the shape fill to have an alpha, use the CSS rgba(r, g, b, alpha) functional-notation style. Use integer values between 0 and 255 for the r, g, and b parameters. The alpha parameter contains a float value, between 0.0 and 1.0, indicating the alpha channel value, which determines the opacity of the color.

You can also set the fill style to be a gradient or pattern. Use the createLinearGradient, createRadialGradient, and createPattern methods to define a style that you can apply to this property.

context.globalAlpha

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.

context.globalCompositeOperation

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 source-over compositing mode.

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.

context.lineCap

A string value that determines the end style used when drawing a line. Specify the string "butt" for a flat edge that is perpendicular to the line itself, "round" for round endpoints, or "square" for square endpoints. If you do not set this value explicitly, the canvas uses the "butt" line cap style.

context.lineJoin

A string value that determines the join style between lines. Specify the string "round" for round joins, "bevel" for beveled joins, or "miter" for miter joins. If you do not set this value explicitly, the canvas uses the "miter" line cap style.

context.lineWidth

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.

context.miterLimit

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 "miter", the canvas uses the miter limit to determine whether the lines should be joined with a bevel instead of a miter. The canvas divides the length of the miter by the line width. If the result is greater than the miter limit, the style is converted to a bevel.

context.shadowBlur

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.

context.shadowColor

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 "#RRGGBB", which represents an RGB color using hexidecimal numbers.

If you want the shadow color to have an alpha, use the CSS rgba(r, g, b, alpha) functional-notation style. Use float values between 0 and 255 for the r, g, and b parameters. The alpha parameter contains a float value, between 0.0 and 1.0, indicating the alpha channel value, which determines the opacity of the color.

context.shadowOffsetX

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.

context.shadowOffsetY

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.

context.strokeStyle

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 "#RRGGBB", which represents an RGB color using hexidecimal numbers.

If you want the shape stroke to have an alpha, use the CSS rgba(r, g, b, alpha) functional-notation style. Use float values between 0 and 255 for the r, g, and b parameters. The alpha parameter contains a float value, between 0.0 and 1.0, indicating the alpha channel value, which determines the opacity of the color.

You can also set the stroke style to be a gradient or pattern. Use the createLinearGradient, createRadialGradient, and createPattern methods to define a style that you can apply to this property.

Table 1-2 describes the operators supported by the context.globalCompositeOperation property. Use these to define the compositing operators for the canvas object.

Table 1-2  Composite operators used by the globalCompositeOperation property

Operator

Description

copy

Displays the source image instead of the destination image.

darker

Display the sum of the source image and destination image, with color values approaching 0 as a limit.

destination-atop

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.

destination-in

Display the destination image wherever both the destination image and source image are opaque. Display transparency elsewhere.

destination-out

Display the destination image wherever the destination image is opaque and the source image is transparent. Display transparency elsewhere.

destination-over

Display the destination image wherever the destination image is opaque. Display the source image elsewhere.

lighter

Display the sum of the source image and destination image, with color values approaching 1 as a limit.

source-atop

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.

source-in

Display the source image wherever both the source image and destination image are opaque. Display transparency elsewhere.

source-out

Display the source image wherever the source image is opaque and the destination image is transparent. Display transparency elsewhere.

source-over

Display the source image wherever the source image is opaque. Display the destination image elsewhere.

xor

Exclusive OR of the source and destination images. Works only with black and white images and is not recommended for color images.

Tasks

Canvas State Methods

Working With Paths

Stroking a Path

Filling an Area

Creating Gradient and Pattern Styles

Drawing an Image

Methods

addColorStop

(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)

Discussion

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.

Availability
See Also

arc

Adds an arc of a circle to the current subpath.

context.arc(x, y, radius, startAngle, endAngle, clockwise)

Discussion

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.

Availability
See Also

arcTo

Adds an arc of a circle to the current subpath, using a radius and tangent points.

context.arcTo(x1, y1, x2, y2, radius)

Discussion

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).

Availability
See Also

beginPath

Creates a new empty path in the canvas.

context.beginPath()

Discussion

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.

Availability
See Also

bezierCurveTo

Appends a cubic Bézier curve to the current path.

context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

Discussion

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.

Availability
See Also

clearRect

Paints a transparent rectangle.

context.clearRect(x, y, width, height)

Discussion

When you call this method, the canvas effectively “erases” the contents of the specified rectangle. The parameters of this method all contain float values.

Availability
See Also

clip

Sets the current clipping path, using the nonzero winding number rule.

context.clip()

Discussion

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.

Availability
See Also

closePath

Closes and terminates an open subpath.

context.closePath()

Discussion

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.

Availability
See Also

createLinearGradient

Returns a gradient object representing a linear gradient.

context.createLinearGradient(x0, y0, x1, y1)

Discussion

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.

Availability
See Also

createPattern

Returns a pattern object representing a repeating pattern.

context.createPattern(image, repetition)

Discussion

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:

Table 1-3  Possible values for createPattern’s repetition parameter

Value

Description

"repeat"

Repeat the image in both the x and y directions.

"repeat-x"

Repeat the image in the x direction.

"repeat-y"

Repeat the image in the y direction.

"no-repeat"

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.

Availability

createRadialGradient

Returns a gradient object representing a radial gradient.

context.createRadialGradient(x0, y0, r0, x1, y1, r1)

Discussion

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.

Availability
See Also

drawImage

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)

Discussion

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.

Availability

drawImageFromRect

Discussion

This method has been depreciated. See drawImage for more information.

fill

Paints the area within the current path, using the nonzero winding-number fill rule.

context.fill()

Discussion

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.

Availability
See Also

fillRect

Paints the area within the specified rectangle.

context.fillRect(x, y, width, height)

Discussion

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.

Availability
See Also

lineTo

Appends a straight line segment from the current point to the point you specify.

context.lineTo(x, y)

Discussion

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.

Availability
See Also

moveTo

Begins a new subpath at the point you specify.

context.moveTo(x, y)

Discussion

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:

Availability
See Also

quadraticCurveTo

Appends a quadratic Bézier curve to the current path.

context.quadraticCurveTo(cpx, cpy, x, y)

Discussion

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.

Availability
See Also

rect

Adds a new subpath, consisting of a single rectangle, to the canvas.

context.rect(x, y, width, height)

Discussion

The parameters for this method all contain float values.

Availability
See Also

restore

Restores the current graphics state to the state most recently saved.

context.restore()

Discussion

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.

Availability
See Also

rotate

Rotates the user coordinate system of the canvas.

context.rotate(angle)

Discussion

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.

Availability
See Also

save

Saves a copy of the current graphics state.

context.save()

Discussion

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.

  1. Modify the graphics state by changing the fill color to blue.

  2. Save the graphics state.

  3. Fill a shape—the shape is painted with blue.

  4. Set the fill color to green.

  5. Fill a shape—the shape is painted with green.

  6. Restore the graphics state.

  7. 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:

Availability
See Also

scale

Changes the scale of the canvas coordinate system.

context.scale(sx, sy)

Discussion

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.

Availability
See Also

stroke

Paints a line along the current path.

context.stroke()

Discussion

To modify the behavior of this method, you can change any of the following graphics state properties:

Availability
See Also

strokeRect

Paints an outline of a rectangle.

context.strokeRect(x, y, width, height)

Discussion

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:

Availability
See Also

translate

Changes the origin of the canvas coordinate system.

context.translate(tx, ty)

Discussion

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.

Availability
See Also


Next Page > Hide TOC


Last updated: 2005-10-04




Did this document help you?
Yes: Tell us what works for you.

It’s good, but: Report typos, inaccuracies, and so forth.

It wasn’t helpful: Tell us what would have helped.
Get information on Apple products.
Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Copyright © 2007 Apple Inc.
All rights reserved. | Terms of use | Privacy Notice