Browser

HTML5: Working with the canvas element

Ryan Boudreaux introduces the <canvas> element in HTML5 and how to work with it to create different shapes and styles.</canvas>
The HTML5 specification has added many new conditions including attributes, semantic markup, and refined elements, sectional elements, and structural elements.  This segment will review the canvas <canvas> element while using JavaScript to draw several canvas shapes. The Canvas <canvas> element allows for a dynamic rendering of bitmap images and 2D shapes onto web pages such as color fill backgrounds, gradient and pattern displays, rendering of text, pixel manipulations, animations, and other visual objects on the fly; therefore, the canvas element becomes a simple pixel-based drawing API tool.

Current browsers which support the HTML5 specification for the canvas element are: IE 9.0+, Safari 3.0+, Firefox 3.0+, Chrome 3.0+, Opera 10.0+, iOS 1.0+, and Android 1.0+.

This is the canvas element in its simplest form:

<canvas id="canvas" width=300" height="150"></canvas>

The canvas element has two default coordinate space attributes, a width of 300px and a height of 150px, the width and height can be modified within the element, and by itself the element renders an invisible block of space. We are giving the canvas element an id="canvas" attribute so that added context can be accessed via JavaScript.

It is also a best practice to add fallback content to the canvas element so that users who employ browsers that do not support the element will see the message as in the example code below:

 <canvas id="canvas" width="175" height="175">
 <!-- Fallback content -->
  <p>We apologize, your browser does not support canvas at this time!</p>
 </canvas>

The example fallback content as displayed in IE8:

Figure A

Coordinates

In the 2D graphics world -- and for the canvas element -- the coordinate system is utilized to establish x-axis and a y-axis values (x,y), where in the uppermost left-hand corner of the graph are coordinates (0,0). Increasing the value of the x-axis will move or float the object to the right, and increasing the value of the y-axis will float the object down.

Canvas rectangle

This example will demonstrate the canvas element with a simple draw script and styling rendering the space visible by assigning border and color attributes.

For the canvas element we need to add the drawing context and styling as in the example below:

<body onLoad="draw();">
<script>
function draw(){
var canvas = document.getElementById('canvas');
if (canvas.getContext){
var context = canvas.getContext('2d');
}
}
</script>
<style>
canvas {
        border: 1px solid #CC0000;
        margin-left:50px;
}
</style>
  <article>
    <h1>Canvas</h1>
    <!-- canvas element tag -->
    <canvas id="canvas" width="175" height="175">
     <p>We apologize, your browser does not support canvas at this time!</p>
    </canvas>
    </article>
 </body>

The HTML above will render the following as displayed in the screen capture taken from the browser Firefox 3.6:

Figure B

Utilizing the fillStyle() function I am going to demonstrate an example of adding several lightly hued fills into rectangle shapes to the canvas area using new CSS3 RGBa color space value settings. RGBa means red green blue and the "a" represents the alpha opacity in decimal values, and is represented in the HTML form of rgba(R, G, B, 0.a). Where the alpha "a" values between 0% and 100% make it possible for pixels to show through a background similar to a glass translucency.

As you can see from the coding examples, the canvas element has a DOM method called getContext, which is used to render context and its drawing function methods, and getContext( string contextId) takes the type of context parameter, which in this case will be set to 2D. By adding the fillStyle and fillRect functions to the script, the canvas draws two translucent box shapes. There are four parameters for the fillRect(x, y, w, h) function method, which defines the position of the upper-left-hand corner, its float width and float height, and is expressed in the form fillRect(float x, float y, float width, float height);.

<body onLoad="draw();">
<script>
function draw(){
var canvas = document.getElementById('canvas');
if (canvas.getContext){
var context = canvas.getContext('2d');
// Draw the canvas shape and define the styles
context.fillStyle = "rgba(93,179,199,0.30)";
context.fillRect (15, 10, 120, 60);
context.fillStyle = "rgba(199,73,193,0.40)";
context.fillRect (55, 30, 120, 60);
}
}
</script>
    <canvas id="canvas" width="175" height="175">
    <!-- Fallback content -->
    <p>We apologize, your browser does not support canvas at this time!</p>
    </canvas>
</body>

The resulting canvas is shown in the screen capture as displayed in Firefox 3.6:

Figure C

Draw a canvas circle using paths

In this example, we will call the function drawCanvas when the document is on load and draw a circle on the empty canvas element, then fill the circle using the fillStyle method with rgba parameters. Always start a canvas drawing path with the function method beginPath(); for the circle path we will use the arc(float x, float y, float radius, float endAngle, boolean anticlockwise), and all canvas drawings must end with the closePath(), and fill() function methods so that the color will fill into the drawing. Draw a canvas circle in this example with the JavaScript shown below:

<body onLoad="drawCanvas();">
 <script>
 function drawCanvas() {
 var circle_canvas = document.getElementById("canvas");
 var canvas_context = circle_canvas.getContext("2d");
//Draw the canvas and define the styles
 canvas_context.fillStyle = "rgba(93,179,199,0.20)";
 canvas_context.beginPath();
 canvas_context.arc(85,85,80,0,Math.PI*2,true);
// Close the path
 canvas_context.closePath();
// Fill the path with color
 canvas_context.fill();
 }
</script>
    <canvas id="canvas" width="175" height="175">
    <!-- Fallback content -->
    <p>We apologize, your browser does not support canvas at this time!</p>
    </canvas>
</body>

The resulting circle canvas in Firefox 3.6 is shown in the screen capture:

Figure D

Canvas drawing other shapes with paths

When drawing shapes with the canvas element we will be utilizing the function methods including those used in the previous example; in addition, we will employ the moveTo(float x, float y) function, which sets the starting point, the lineTo(float x, float y) function which draws a straight path from the previous point that is defined in the moveTo() function, or the last point that is drawn by lineTo() function, and the stroke() function is used to fill the outline of the function.

Canvas triangle shape

The example code below will demonstrate drawing a right triangle shape:

<script>
function drawCanvas() {
var triangle = document.getElementById("triangle");
var context = triangle.getContext("2d");
//Draw the canvas shape
context.beginPath();
context.moveTo(175,0);
context.lineTo(175,100);
context.lineTo(15,100);
//Close the path and fill with default color
context.closePath();
context.fill();
}
</script>
<h1>Canvas Examples</h1>
<h2>Triangle Shape</h2>
    <!-- canvas circle element tag -->
    <canvas id="triangle" width="175" height="175">
    <!-- Fallback content -->
    <p>We apologize, your browser does not support canvas at this time!</p>
    </canvas>

The resulting canvas right triangle shape as displayed in Firefox 3.6:

Figure E

Want to make this an equilateral triangle? Easy, just change the points to this:

context.moveTo(75,0);
context.lineTo(150,100);
context.lineTo(0,100);

Resulting in an equilateral triangle shape as represented in Firefox 3.6:

Figure F

How about a diamond shape? Just add another lineTo() point between the two existing points:

context.lineTo(75, 200);

The following diamond shape is shown in Firefox 3.6:

Figure G

Just as we customized the canvas rectangle and circle fills with color, we can also change the default black fill with something more pleasing. Let's add some line styling using the fillStyle and strokeStyle functions along with the lineWidth function which sets the width of the outline. When adding styling and fill functions to your canvas, be sure to set the styling after the draw shape functions, and then close the path, and then set the fill and stroke functions last. The example code is shown below:

<script>
function drawCanvas() {
var diamond = document.getElementById("diamond");
var context = diamond.getContext("2d");
// Draw the canvas shape
context.beginPath();
context.moveTo(75,0);
context.lineTo(150,100);
context.lineTo(75, 200);
context.lineTo(0,100);
// Define the style of the canvas shape
context.lineWidth = 1;
context.fillStyle = "rgba(199, 73, 193, .2)";
context.strokeStyle = "rgba(100, 125, 200, .8)";
// Close the path
context.closePath();
// Fill the path with a colored outline
context.fill();
context.stroke();
}
</script>
    <h1>Canvas Examples</h1>
    <h2>Diamond Shape</h2>
    <!-- canvas circle element tag -->
    <canvas id="diamond" width="200" height="200">
    <!-- Fallback content -->
    <p>We apologize, your browser does not support canvas at this time!</p>
    </canvas>

Below is the stylized triangle shape as displayed in Firefox 3.6:

Figure H

These simple shapes are just a start and there are endless ways in which you can manipulate 2D drawings using the canvas element with on the fly JavaScript.

The next segments on HTML5 will review more fun canvas element projects including drawing images with canvas, and adding text. And future segments on HTML5 will review more elements including the audio <audio> element, the video <video> element, the figure <figure> element, the figure caption <figcaption> element and more.

About

Ryan has performed in a broad range of technology support roles for electric-generation utilities, including nuclear power plants, and for the telecommunications industry. He has worked in web development for the restaurant industry and the Federal g...

4 comments
l_e_cox
l_e_cox

The newer CSS webkits allow you to apply 3d effects to HTML elements (tables, divs, etc). For me, that seems like a more interesting possibility. The canvas element allows you to provide moving graphical elements on a page without refresh. They can respond to mouse movements, etc. But I have always found these to be a distraction unless they are actually integrated into the page content for navigation purposes or something like that. What canvas can do besides offering dynamic graphical content is give you visual design elements that aren't boxes. But I would prefer that this be done by adding new style commands that would modify the appearance of HTML elements to make them curve or bend.

Spitfire_Sysop
Spitfire_Sysop

Have you tried using 3D canvas? I wonder how difficult it is to drop in objects.