Search This Blog

Showing posts with label HTML5. Show all posts
Showing posts with label HTML5. Show all posts

Monday, January 3, 2011

Drawing Basic Shapes with HTML5 Canvas (last Part)

Welcome back to another edition of "Drawing Basic Shapes with HTML5 Canvas." Here are the links to the first three parts: part 1, part 2 and part 3

This post will cover the last part of the series. Specifically, we'll draw a circle using HTML5 Canvas. If you find the explanation difficult to understand, please review the previous parts of the tutorial. I covered a lot of basic information in those parts.

Alright, here we go!

Circle:

As usual, please check out the code first and try to see if you can understand it. Then, you can read the explanation.

<!DOCTYPE HTML>
  <html>
    <body>
      <canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
        Your browser does not support the canvas element.
      </canvas>
      <script type="text/javascript">
        var c=document.getElementById("myCanvas");
        var cxt=c.getContext("2d");
        cxt.fillStyle="#FF0000";
        cxt.beginPath();
        cxt.arc(70,18,15,0,Math.PI*2,true);
        cxt.closePath();
        cxt.fill();
      </script>
    </body>
  </html>
<canvas>: as usual, we define a canvas with specified dimension and id. We also make the canvas border visible for easy drawing.

<script>: we first get a reference to our canvas and then get the its 2D drawing context. If you don't know what a context is, please review the second part of the tutorial. 

  1. fillStyle(): use red color to fill our circle.
  2. beginPath(): this method creates a new path for custom drawings. What is a path? It is a collection of different sketches and strokes. A shape is considered a path because a shape is made up of many different strokes (lines, arcs, ...). Each path has its own properties such as stroke color and fill color. 
  3. arc(): draw an arc or a circle. The full method signature is arc( center_x, center_y, radius, startAngle, endAngle, antiClockwise). 
center_x and center_y: the coordinates of the center of the circle or arc. 
radius: radius of the circle / arc.
startAngle and endAngle: start and end point of the circle / arc in radian. If you forgot your trigonometry,  use this JavaScript formula to convert degree to radian (Math.Pi / 180) * degree. Since we draw circle, we need to start our angle at 0 and end our angle at 360 degree or PI * 2. 
antiClockwise: a boolean that is true to draw the circle / arc anti-clockwise and false to do the opposite.
closePath(): end the path after we has done our drawing. When drawing many different shapes on the same canvas, we must call beginPath() and closePath() for each shape.
fill(): fill our circle with specified color (red).
Here is a picture. Hope it helps to clear up any confusion:


Well, that concludes our tutorial. If you have any question / suggestion please leave it in the comment below. 

I'm preparing for more advanced tutorial on HTML5 Canvas! So check back for more goodies later :)

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 :)




Saturday, December 25, 2010

Drawing Basic Shapes with HTML5 Canvas (Part 2)

Hello and welcome to the second part of "Drawing Basic Shapes with HTML5" series. If you haven't looked at the first part, you can read it here. The first part covers the basics about the coordinate system that  HTML5 Canvas uses. In this second part, we will apply that knowledge into drawing a simple rectangle in HTML5 Canvas.

Before going into more details, I want to warn you that not all browsers support HTML5. And each browser supports HTML5 differently. The reason is that HTML5 is not finalized yet, so some browsers decide to support certain tags while the others don't. Fortunately, HTML5 Canvas is supported by most major browsers. If you are using the updated version of Firefox, Chrome, Safari or Opera, you are golden for this tutorial. But if you're using IE8 or earlier, change your browser now!! 

Rectangle:

Take a look at the code first and I'll explain it line by line:

<!DOCTYPE HTML>
 <html>   
  <body>
    <canvas id="myCanvas" width="150" height="75" style="border:1px solid #c3c3c3;">        
    Your browser does not support the canvas element.     
    </canvas>
    <script type="text/javascript">       
     var c=document.getElementById("myCanvas");          
     var cxt=c.getContext("2d");        
     cxt.fillStyle="#FF0000";      
     cxt.fillRect(0,0,100,50);      
    </script>
  </body>
</html>

1. HTML5 Doctype declaration: you can see how much it is different from that of HTML4. It's much simpler and easier to remember! Just that one line will trigger the standard mode in HTML5-supporting browsers.

2. <canvas> tags: these tags let browsers know that we want to insert a canvas into our web page. 
  • id: like the canvas' name. JavaScript uses it to identify one canvas from another 
  • width and height: specify how big the canvas is. Remember that a canvas is just a drawable area on your page. Its shape is always a rectangle. You draw things inside that rectangle.
  • style: I use it to show the invisible rectangle that defines the canvas. Without the visible border, it's hard to know where our drawable area is. We make it visible for now and make it disappear later after finishing our drawing.
  • text inside <canvas> tags: we put some text inside the tags, so that if a browser doesn't support HTML5, the text will be displayed, letting users know what's wrong. This is called graceful degradation :)
3. <script> tags: next we have a JavaScript code which is used to draw things on the canvas. Why we need JavaScript? Well, remember that the canvas is only a drawable area. It is not responsible for any drawing. Therefore, we must use other technologies to draw on it. In this case, we use JavaScript because it is easy and popular scripting language for the web. 
  • First, we get a reference to our canvas using the canvas' id
  • Second, we get a reference to our canvas drawing context which is in 2D. A drawing context is like a set of properties that our drawing has. For example, color and dimension are properties of a drawing.
  • Third, we set the fillStyle property to red color. This means that our rectangle will be a solid rectangle.
  • Fourth, we define the drawing dimension property of our rectangle. Our rectangle will be drawn from the origin of the canvas which is point (0, 0) on the coordinate system. Moreover, the rectangle's width is 100 pixels and its height is 50 pixels. Confused? Take a look at this picture and maybe re-read the first part of this series :P



Copy and paste that entire code into a text editor such as WordPad, Text or Gedit (remember to use plain-text mode) and save it as a .html file and open it with your browser to see the result for yourself. 

In the next part, we'll use different techniques to draw the remaining shapes: triangle and circle. As always, please leave a comment below and let me know what you think :)





Tuesday, December 21, 2010

Drawing Basic Shapes with HTML5 Canvas (Part 1)

The new HTML standard, called HTML5, has gained so much attention right now. It is supposed to be one of the tools to create cross-platform web applications, the so-called Flash-less / plugin-less. Check out these games on this website http://html5games.com. They are all created using HTML5, JavaScript and CSS. No Flash at all and no third-party plugin needed :) Very nice right?! I was impressed by the variety of games that can be created using HTML5.

Anyway, in this tutorial, we'll learn to how to draw basic shapes using one of the new tags in HTML5, the Canvas tag. Basic shapes include rectangle, triangle and circle.
However, before drawing anything, we must learn about the coordinate system that HTML5 Canvas uses.

What is a coordinate system?

A coordinate system is a map. Each point on that map has values associated with it. Those values are used to identify the point and where the point is on the map relative to the map's origin.

HTML5 employs the Cartesian coordinate system. You definitely learned it in high-school math. But I assume you forget about it already, so here is what a Cartesian coordinate system looks like. 

Please notice that this is the 2D version of the system. There is the 3D version too but we don't worry about it now. 

You can see that each point has a pair of values associated with it. These are called the coordinates of the point and usually denoted as (x, y). X is the position of the point according to the horizontal axis and Y is the position of the point according to the vertical axis. And we need both to locate a point.

For example, point (2, 3) has x value of 2 and y value of 3. How do we know that? Draw a perpendicular line from our point to the x-axis and record the value marked on the x-axis. That value is the x coordinate of our point. Do the same thing for the y axis to get the y coordinate. The origin is a special point whose coordinate is (0, 0).

Coordinate System in HTML5 Canvas

Now back to HTML5. It only uses the 4th quadrant of the Cartesian coordinate system. That means that only the shaded / red-bound portion is used: 


The origin locates at the top-left corner of the canvas rectangular area and the top edge is the x-axis while the left edge is the vertical axis:


This is an important concept because to draw a shape in HTML5 Canvas, you must know the points and their coordinates on the Canvas coordinate system. It is like connecting dots to create a picture. Those dots are your points on the coordinate system and your picture is the shape you want to draw.

That's enough for this post. Take your time to understand this concept. In the next part, we'll go straight to coding :)