Friday, September 12, 2008

HTML Canvas Element - Part 2

In Part 1 of the series we set up a simple template to build the rest of the example on.

Our goal is to display a triangle and allow the user to zoom in and zoom out.

In this part we will display a black triangle on a white background. Replace your draw function with this one and then refresh your browser.

function draw() {
// Get Reference to the 'canvas' tag
var canvas = document.getElementById("canvas");
if (canvas.getContext){
// Get a context that allows us to draw on.
var ctx = canvas.getContext('2d');

// Move cursor and draw the outline of the Triangle
ctx.beginPath();
ctx.moveTo(0,100);
ctx.lineTo(50,0);
ctx.lineTo(100,100);
ctx.lineTo(0,100);

// Actually Draw, you could call stroke instead which will draw the outline
ctx.fill();
}

}


You should now see a black triangle on a white background. The code got a drawing context by calling canvas.getContext("2d").

We then use the moveTo command which picks up the cursor and moves to the location without drawing. Notice the coordinate system starts in the upper left with x extending to the right and y extending down.

We start our path with beginPath(). This will clear out any other draw commands and now your ready to trace your path with lineTo. One we have traced our triangle with the lineTo commands we call 'ctx.fill()' Which draws the shape and fills it with a solid color. Alternatively we could of called 'ctx.stroke()' which will draw the outline.

Continue to Part 3 to learn how to Zoom in/out the triangle.

1 comment:

Anna Schafer said...

Through this we can add different buttons, tools, meus, system tools, dockable window, palette etc and also can organize them.Javascript for table add