Section 25.11. CanvasRenderingContext2D: the object used for drawing on a canvas


25.11. CanvasRenderingContext2D: the object used for drawing on a canvas

Firefox 1.5, Safari 1.3, Opera 9: Object CanvasRenderingContext2D

25.11.1. Properties


readonly Canvas canvas

The Canvas element upon which this context will draw.


Object fillStyle

The current color, pattern, or gradient used for filling paths. This property may be set to a string or to a CanvasGradient or CanvasPattern object. When set to a string, it is parsed as a CSS color value and used for solid fills. When set to a CanvasGradient or CanvasPattern object, fills are done using the specified gradient or pattern. See CanvasRenderingContext2D.createLinearGradient( ), CanvasRenderingContext2D.createRadialGradient( ), and CanvasRenderingContext2D.createPattern( ).


float globalAlpha

Specifies the opacity of content drawn on the canvas. The range of values is between 0.0 (fully transparent) and 1.0 (no additional transparency). The default value for this property is 1.0.


String globalCompositeOperation

Specifies how colors being drawn are combined (or "composited") with colors already on the canvas. See the individual reference entry for this property for possible values.


String lineCap

Specifies how the ends of lines are rendered. Legal values are "butt", "round", and "square". The default is "butt". See the individual reference page for this property for further details.


String lineJoin

Specifies how two lines are joined. Legal values are "round", "bevel", and "miter". The default is "miter". See the individual reference page for this property for further details.


float lineWidth

Specifies the line width for stroking (line drawing) operations. The default is 1.0, and this property must be greater than 0.0. Wide lines are centered over the path, with half of the line width on each side.


float miterLimit

When the lineJoin property is "miter", this property specifies the maximum ratio of miter length to line width. See the individual reference page for this property for further details.


float shadowBlur

Specifies how much feathering shadows should have. The default is 0. Shadows are supported by Safari but not by Firefox 1.5 or Opera 9.


String shadowColor

Specifies the color of shadows as a CSS or web style string and may include an alpha component for transparency. The default is black. Shadows are supported by Safari but not by Firefox 1.5 or Opera 9.


float shadowOffsetX, shadowOffsetY

Specify the horizontal and vertical offset of the shadows. Larger values make the shadowed object appear to float higher above the background. The default is 0. Shadows are supported by Safari, but not by Firefox 1.5 or Opera 9.


Object strokeStyle

Specifies the color, pattern, or gradient used for stroking (drawing) paths. This property may be a string, or a CanvasGradient or a CanvasPattern object. If it is a string, it is parsed as a CSS color value and the stroking is done with the resulting solid color. If the value of this property is a CanvasGradient or a CanvasPattern object, stroking is done with a gradient or pattern. See CanvasRenderingContext2D.createLinearGradient( ), CanvasRenderingContext2D.createRadialGradient( ), and CanvasRenderingContext2D.createPattern( ).

25.11.2. Methods


arc( )

Adds an arc to the current subpath of a canvas, using a center point and radius.


arcTo( )

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


beginPath( )

Starts a new path (or a collection of subpaths) in a canvas.


bezierCurveTo( )

Adds a cubic Bézier curve to the current subpath.


clearRect( )

Erases the pixels in a rectangular area of a canvas.


clip( )

Uses the current path as the clipping region for subsequent drawing operations.


closePath( )

Closes the current subpath if it's open.


createLinearGradient( )

Returns a CanvasGradient object that represents a linear color gradient.


createPattern( )

Returns a CanvasPattern object that represents a tiled image.


createRadialGradient( )

Returns a CanvasGradient object that represents a radial color gradient.


drawImage( )

Draws an image.


fill( )

Paints or fills the interior of the current path with the color, gradient, or pattern specified by the fillStyle property.


fillRect( )

Paints or fills a rectangle.


lineTo( )

Adds a straight line segment to the current subpath.


moveTo( )

Sets the current position and begins a new subpath.


quadraticCurveTo( )

Adds a quadratic Bézier curve to the current subpath.


rect( )

Add a rectangle subpath to the current path.


restore( )

Resets the canvas to the graphics state most recently saved.


rotate( )

Rotates the canvas.


save( )

Saves the properties, clipping region, and transformation matrix of the CanvasRenderingContext2D object.


scale( )

Scales the user coordinate system of the canvas.


stroke( )

Draws, or strokes, a line following the current path. The line is drawn according to the lineWidth, lineJoin, lineCap, and strokeStyle properties, among others.


strokeRect( )

Draws (but does not fill) a rectangle.


translate( )

Translates the user coordinate system of the canvas.

25.11.3. Description

The CanvasRenderingContext2D object provides a set of graphics functions to draw on a canvas. While text support is unfortunately omitted, the functions available are quite rich. They fall into a number of categories.

25.11.3.1. Drawing rectangles

You can outline and fill rectangles with strokeRect( ) and fillRect( ). In addition, you can clear the area defined by a rectangle with clearRect( ).

25.11.3.2. Drawing images

In the Canvas API, images are specified using Image objects that represent HTML <img> elements or offscreen images created with the Image( ) constructor. (See the Image reference page for details.) A canvas object can also be used as an image source.

You can draw an image into a canvas with the drawImage( ) method, which, in its most general form, allows an arbitrary rectangular region of the source image to be scaled and rendered into the canvas.

25.11.3.3. Creating and rendering paths

A powerful feature of the canvas is its ability to build shapes up from basic drawing operations, then either draw their outlines (stroke them) or paint their contents (fill them). The operations accumulated are collectively referred to as the current path. A canvas maintains a single current path.

In order to build a connected shape out of multiple segments, a joining point is needed between drawing operations. For this purpose, the canvas maintains a current position. The canvas drawing operations implicitly use this as their start point and update it to what is typically their end point. You can think of this like drawing with a pen on paper: when finishing a particular line or curve, the current position is where the pen rested after completing the operation.

You can create a sequence of disconnected shapes in the current path that will be rendered together with the same drawing parameters. To separate shapes, use the moveTo( ) method; this moves the current position to a new location without adding a connecting line. When you do this, you create a new subpath, which is the canvas term used for a collection of operations that are connected.

Once the path is formed to your liking, you can draw its outline with stroke( ), paint its contents with fill( ), or do both.

The available shape operations are lineTo( ) for drawing straight lines, rect( ) for drawing rectangles, arc( ) or arcTo( ) for drawing partial circles, and bezierCurveTo( ) or quadraticCurveTo( ) for drawing curves.

In addition to stroking and filling, you can also use the current path to specify the clipping region the canvas uses when rendering. Pixels inside this region are displayed; those outside are not. The clipping region is cumulative; calling clip( ) intersects the current path with the current clipping region to yield a new region. Unfortunately, there is no direct method for resetting the clipping region to the extent of the canvas; to do so, you must save and restore the entire graphics state of the canvas (described later in this entry).

If the segments in any of the subpaths do not form a closed shape, fill( ) and clip( ) operations implicitly close them for you by adding a virtual (not visible with a stroke) line segment from the start to the end of the subpath. Optionally, you can call closePath( ) to explicitly add this line segment.

25.11.3.4. Colors, gradients, and patterns

When filling or stroking paths, you can specify how the lines or painted area are rendered using the fillStyle and strokeStyle properties. Both accept CSS-style color strings, as well as CanvasGradient and CanvasPattern objects that describe gradients and patterns. To create a gradient, use the createLinearGradient( ) or createRadialGradient( ) methods. To create a pattern, use createPattern( ).

To specify an opaque color using CSS notation, use a string of the form "#RRGGBB", where RR, GG, and BB are hexadecimal digits that specify the red, green, and blue components of the color as values between 00 and FF. For example, bright red is "#FF0000". To specify a partially transparent color, use a string of the form "rgba(R,G,B,A)". In this form, R, G, and B specify the red, green, and blue components of the color as decimal integers between 0 and 255, and A specifies the alpha (opacity) component as a floating-point value between 0.0 (fully transparent) and 1.0 (fully opaque). For example, half-transparent bright red is "rgba(255,0,0,0.5)".

25.11.3.5. Line width, line caps and line joins

Canvas offers several options for tailoring how lines appear. You can specify the width of the line with the lineWidth property, how the end points of lines are drawn with the lineCap property, and how lines are joined using the lineJoin property.

25.11.3.6. Coordinate space and transformations

By default, the coordinate space for a canvas has its origin at (0,0) in the upper-left corner of the canvas, with x values increasing to the right and y values increasing down. A single unit in this coordinate space normally translates to a single pixel.

You can, however, transform the coordinate space, causing any coordinates or extents you specify in drawing operations to be shifted, scaled, or rotated. This is done with the translate( ), scale( ), and rotate( ) methods, which affect the transformation matrix of the canvas. Because the coordinate space can be transformed like this, the coordinates you pass to methods such as lineTo( ) may not be measured in pixels. For this reason, the Canvas API uses floating-point numbers instead of integers.

Transformations are processed in reverse of the order in which they are specified. So, for example, a call to scale( ) followed by a call to TRanslate( ) causes the coordinate system first to be translated, then scaled.

25.11.3.7. Compositing

Commonly, shapes are drawn on top of one another, with the new shape obscuring any shapes that were previously drawn below it. This is the default behavior in a canvas. However, you can perform many interesting operations by specifying different values for the globalCompositeOperation property. These range from XORing to lightening or darkening shaped regions; see CanvasRenderingContext2D.globalCompositeOperation for all the possible options.

25.11.3.8. Shadows

The Canvas API includes properties that can automatically add a drop shadow to any shape you draw. At the time of this writing, Safari is the only browser that implements this API, however. The color of the shadow may be specified with shadowColor, and its offset changed using shadowOffsetX and shadowOffsetY. In addition, the amount of feathering applied to the shadow's edge may be set with shadowBlur.

25.11.3.9. Saving graphics state

The save( ) and restore( ) methods allow you to save and restore the state of a CanvasRenderingContext2D object. save( ) pushes the current state onto a stack, and restore( ) pops the most recently saved state off the top of the stack and sets the current drawing state based on those stored values.

All properties of the CanvasRenderingContext2D object (except for the canvas property, which is a constant) are part of the saved state. The transformation matrix and clipping region are also part of the state, but the current path and current point are not.

25.11.4. See Also

Canvas




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net