From an HTML perspective, creating a canvas is nothing special. It's just a regular tag with no extraordinary attributes or syntax. To create a canvas, use:
<canvas id=”myID” width=”width” height=”height”> fallback text </canvas>
The fallback text is displayed only if a user’s browser doesn’t support this element.
Unlike the rest of HTML, you shouldn’t use CSS to set the width and height of the canvas. The canvas defaults to a size of
300px (width) by
150px (height), and if you set a width or height with CSS, it simply stretches or shrinks the original canvas image to be this size. Sometimes you want that, but more often than not you don’t. If you want your canvas to be a specific size, set the
height attributes on the canvas element itself.
And last but not least, we need to set an
Accessing the canvas can be done in the same way you’d access any other element, with
getElementById(), but that is not enough if we want to draw something on it. We need to access the part of the element that is responsible for drawing, which is done with
getContext(‘2d’). Any time I refer to the context in this course, I mean this 2D context of the canvas. Any and every canvas method should be applied to its context, and not the element itself.
<canvas id="myCanvas" width="600" height="300"> <p>Sorry, your browser doesn't support the CANVAS element.</p> </canvas> <script> var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); //Perform canvas operations with the context stored in the ctx variable //For example, creating a rectangle! ctx.fillRect(10,10,100,100); </script>
Before we continue our journey into the world of canvas, I need to clear up one thing. The coordinate system used is not like in traditional mathematics (Cartesian coordinates).
In the traditional system, moving upwards from the origin increases values on the y-axis. In the canvas system, the origin is at the top left corner, and moving downwards increases values on the y-axis.