Tutorial 16 - Graphics and Imaging
<canvas id="canvas" width='100' height='100'> <p>Sorry: Browser does not support Graphics Canvas</p></canvas>
Note: Not all browsers implement the canvas element. Include either a text or image element inside any canvas element to warn users! Also use getContext(apiName) to escape functions that require canvas! Look at the tutorials for Shapes and Styles for examples.
Shapes and Paths
There is only one primitive shape: the rectangle. It has three constructors: clearRect(x,y,width,height), fillRect(x,y,width,height) and strokeRect(x,y,width,height).
Paths are used for more complex shapes. Paths are drawn with beginPath(), moveTo(x,y) [pen up], lineTo(x,y) [pen down], closePath(), stroke() [for outlines] and fill() [for filled shapes].
Arcs are drawn with arc(x,y,radius,sAng,eAng,rotFlag). sAng and eAng are in radians (note: a simple conversion is var radians=(Math.PI/180)*degrees). rotFlag is boolean.
Bezier curves are used to draw complex shapes. They have either one: quadraticCurveTo(cp1x,cp1y,x,y) or two: bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y)control points.
Styles and Patterns
Fill patterns control how a drawn object is filled in with ink. Color is the common fill pattern used. Inkwells are filled with fillStyle=colorVal and strokeStyle=colorVal. colorVal has several formats: hex (eg #rrggbb), named (eg red), rgb (eg rgb(r, g, b)) and alphaTransparency (eg rgba(r, g, b, a).
Line strokes can be styled in several ways. The properties are lineWidth [int], lineCap [butt|round|square] and lineJoin [round|bevel|mitre]. mitreLimit can be set and if exceeded bevel style is forced.
Gradient objects are created with createLinearGradient(x1, y1, x2, y2) or createRadialGradient(x1, y1, r1, x2, y2, r2). colors are added with addColorStop(posn, colorVal). posn can be from 0 to 1.
Pattern objects are created with createPattern(img, repVal). repVal is one of repeat, repeat-x, repeat-y, no-repeat. Refer to next section for img.
Transformations & Composites
Transformation methods include translate, rotate, scale and the generic transform.
Objects are normally placed on top of the canvas, covering previous objects. globalCompositeOperation allows placing under another object or other more complex method of masking.
Clipping provides complex masking screens.
Images can be loaded from a file and drawn to the canvas for editing. Preloading is recommended. They can then be scaled and/or sliced (ie cropped).
Text, Shadows, Fonts
Text can be added to a canvas using the properties: font, textAlign & textBase; and the methods: fillText(txt,x,y[,width]) & strokeText(txt,x,y[,width]). Shadows are drawn using the properties: shadowOffsetX, shadowOffsetY, shadowBlur and shadowColor. The use of text objects in canvas is documented at developer.mozilla.org.