Tutorial 16 - Graphics and Imaging: The Canvas
Tutorial 16 - Graphics and Imaging: The Canvas
Graphics brings life to applications. JavaScript allows creation and modification of images using HTML5 canvasobjects. This basic tutorial introduces some fundamental concepts of graphics and imaging. A more complete tutorial can be found at Mozilla's Canvas Tutorial.
The Canvas
HTML 5 introduces the canvas element which allows JavaScript 2D objects to be used in documents. Artists tend to think in terms of a canvas surface as the foundation for their images and graphics. The canvas origin (0,0) is set at theupper left corner. Output to the canvas takes place through a graphics context encapsulated by the Graphics class.
<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 ahead in the tutorial for Shapes and Styles.
Show Graphic
Show Graphic
Arcs are drawn with arc(x,y,radius,sAng,eAng,rotFlag). sAng and eAng are in radians (note: a simple conversion isvar radians=(Math.PI/180)*degrees). rotFlag is boolean.
Show Graphic
Show Graphic
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.
Show Graphic
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.
Show Graphic
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.
Using Images
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).
Show Graphic