Search This Blog

Wednesday, December 29, 2010

Drawing Basic Shapes with HTML5 Canvas (Part 3)

Hello readers! Welcome to the third part of "Drawing basic shapes with HTML5 Canvas" If you haven't, please read the first part here and the second part here. They cover fundamental knowledge that is necessary to understand this part. For this installment, we'll draw a triangle. Let's do it!


Triangle:


Here is the code, please look over it first to see if you can understand it by yourself.  Then, you can read on to the explanation:

<html>
  <body>


    <canvas id="myCanvas" width="200" height="100" style="border: 1px solid black;">
      Your browser does not support the canvas element.
    </canvas>


    <script type = "text/javascript">
      var canvas = document.getElementById("myCanvas");
      var context = canvas.getContext("2d");
      context.moveTo(10, 10);
      context.lineTo(150, 50);
      context.lineTo(10, 50);
      context.lineTo(10, 10);
      context.stroke();
      context.fill();
    </scrip>


  </body>
</html>

I didn't include header or doctype declaration for the sake of simplicity. So, we'll just focus on the code between the <canvas> tags and the JavaScript code.


<canvas> tags: nothing new here if you read the second part of this tutorial. We create a canvas with specified dimension. We also make the canvas' border visible for easy drawing. Our canvas can be identified / referenced using its id.


<scrip> tags: this is the JavaScript used to draw shapes on the canvas. Recall that canvas is just an drawable area and it can't draw itself. That's why we need to use JavaScript to do the drawing.
  1. Get a reference to our canvas using its id
  2. Get the 2D drawing context of our canvas. Please look at part 2 for explanation of what a canvas context is.
  3. To draw custom shapes such as a triangle, we can't use convenient methods like fillRect(). Therefore, we must draw those shapes ourselves. The process is like this: specify the starting point --> sketch the drawing by using lineTo() --> draw the shapes by calling stroke(). This process is analogous to drawing with pencil and paper. We first choose a starting point for your pencil stroke and from there you drag the pencil to draw things that we want. Moreover, professional artists don't just start drawing with paint immediately. They sketch first with pencil and then draw with paint according to the sketch. 
moveTo(x, y) moves our pencil to point (x , y).
lineTo(x, y) draws a line with pencil from your previous point to the new point specified inside lineTo(x,  y).
stroke() is called when when we're done with pencil sketching.
fill() is called if we want to fill the shape we just create with color.


That's it for now. Stay tuned for the last part where we're gonna draw a circle :)




No comments:

Post a Comment