A Brief Foray Into the Canvas Element: How to Draw Basic Shapes
by Joe Laudato
The first step in conjuring images out of text is setting up a rudimentary canvas template. This consists of both a <canvas> and <script> tag:
<canvas id="exampleCanvas" width="500" height="500"> This text between the canvas tags is displayed when a browser does not support canvas. </canvas> <script> var canvas = document.getElementById('exampleCanvas'); var context = canvas.getContext('2d'); <!--Sketching content--> </script>
This basic canvas template accomplishes several important goals: it defines “exampleCanvas” as a canvas element, it defines the width and height of the canvas in pixels, and presents a browser incompatibility message should the canvas tag fail to work.
Sketching Via Keyboard
Think of the canvas grid as the bottom right-hand quadrant of the Cartesian coordinate plane. At the top left-hand corner of the canvas grid lies the origin, from which a basic canvas line will originate. For example, this code if placed within the <script> and </script> tags will produce a singular vertical line which extends 100 pixels downwards from the origin:
context.beginPath(); context.moveTo(0,100) context.lineTo(0,0) context.stroke();
Upon modifying (0,100) to (40, 100) in the above code, the line’s origin remains at the upper left-hand corner, but the line’s target shifts 40 pixels to the right.
Manipulating the context.lineTo values again in the above code also produces interesting results. While context.moveTo modifies the line’s target, context.lineTo modifies the line’s origin. Setting (25, 0) will shift the origin 25 pixels to the right, and setting (0, 25) will shift the origin 25 pixels downward.
Once you’ve set up one line of “context.lineTo(30, 40)” the origin is redefined as the line’s target [which is in this case (30,40)]. You can define the origin initially with context.moveTo and then set up a chain of context.lineTo’s in order to make a shape. A triangle goes like this:
context.beginPath(); context.moveTo(100, 0); context.lineTo(150, 100); context.lineTo(50, 100); context.lineTo(100, 0); context.stroke(); context.fill();
Fear not; drawing objects is not always so tedious in canvas. Making a rectangle uses a much simpler code:
context.beginPath(); context.fillStyle = 'blue'; context.globalAlpha = .6; context.rect(100, 75, 100,100); context.stroke(); context.fill();
(In this rectangle I’ve also modified its transparency to 60% using context.globalAlpha and it’s fill colour using context.fillStyle. )
A final, easily drawn shape in canvas is a circle, encoded like so:
context.beginPath(); context.globalAlpha = .5; context.fillStyle = 'orange'; context.arc(200,175,50,0,2 * Math.PI, 0); context.stroke(); context.fill();