HTML5 Tutorial : Getting Started with a simple canvas example

 

The example below is a simple canvas example:

 

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>Canvas Line</title>

<script>

function draw_line() {

 

 var canvasObj = document.getElementById("mycanvas");

 var canvasCtx = canvasObj.getContext("2d");

 canvasCtx.moveTo(0, 0);

 canvasCtx.lineTo(200,200);

 canvasCtx.stroke();

}

 

function clear_canvas() {

var canvasObj = document.getElementById("mycanvas");

var canvasCtx = canvasObj.getContext("2d");

        canvasCtx.clearRect(0,0,200,200);

}

</script>

</head>

<body>

    <div id="instructions">

     <a href="#" onclick="draw_line();return false">Click to draw a line</a>

     <a href="#" onclick="clear_canvas();return false">Click to clear</a>

    </div>

 <div id="drawingsurface">

  <canvas id="mycanvas" width="200" height="200"/>

 </div>

</body>

</html>

 

 

The main function to look at is draw_line(). The first thing before we can do any operation with the canvas is to get a handle to the canvas. This is done in a standard fashion via the getDocumentById() method. Now, before you can start invoking any operation on the canvas, you must first get a context to the canvas via the getContext method. The getContext method takes a single parameter and we request a 2D context from the canvas object. Once we have this context object, we can start invoking operations on it.

 

Remember the canvas co-ordinates are (0,0) in the top-left and they increase as you move to the right (x-axis) and down (y-axis).We wish to draw a line from (0,0) to (200,200) i.e. from the top-left corner to the bottom-right corner. This is accomplished by first positioning yourself at the start (0,0) via the moveTo method. Then we use the lineTo(x,y) method and specify that we wish to draw a line till (200,200). This by itself does not accomplish anything. It is more like we have defined a path. Once we are done with the path, we instruct the canvas to render it with the stroke() method.

 

If you look at the clear_canvas() function, you will notice that we are already using the Rectangle drawing support for the Canvas.

For more complete information about compiler optimizations, see our Optimization Notice.
Categories: