HTML 5’s Almost Forgotten Canvas Element
Three of the most talked about elements in HTML 5 are the audio, video, and canvas elements. Much has been written about the audio and video elements, since they are so easily implemented into a web document. However, the canvas element hasn’t experienced the same notoriety as its two counterparts. To correct this oversight, this article discusses the basic information that you need to know in order to use the element. As always when creating new content, make sure not to copy others work, creating the possibility to have a patent lawsuit on your hands. It had happened many times before.
The Canvas Element
Thecanvas element has only one primary function, and that function is to provide a drawing surface for the Canvas Drawing API’s functions, which are also a part of the HTML 5 specification. When the canvas element is used without any default attributes, the element’s default behavior produces a drawing surface dimension of 300 pixels wide and 150 pixels high. To define a drawing surface dimension other than the default, web designers need to define the element’s width and height attribute. Another attribute that may also be defined is the ID attribute. Defining the ID attribute allows for each canvas element in the document to be styled independently using CSS. In addition, the ID attribute also serves another very useful function, which is the subject of the next section.
The Drawing Context
To acquire the context of a particular canvas element, the element must call the getContext method. For example, a canvas with an ID of foo can be called using document.getElementByID(foo).getContext(2D) function call. The getContext method must also include the ‘2D’ argument in the function. Furthermore, the return value of this function call can be stored in a variable. This variable can be used to call the other functions used with the drawing API. For instance, a variable with the name of bar can be used to call the fillStyle or fillRect function. The implementation of this example is shown below.
var bar = document.getElementByID(foo).getContext (2D); bar.fillRect(10,10,100,100);
Types of Drawings
- Rectangles: fillRect(), strokeRect(), clearRect()
- Paths: beginPath(),closePath(), stroke(), fill()
- Arcs: arc()
- Bezier curves: quadraticCurveTo(), bezierCurveTo()
- Images: drawImage()
- Gradients: createLinearGradient(), createRadialGradient()