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




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

Saturday, December 18, 2010

Find the greatest element in an unordered array of elements


To find the element with max value in an unordered array or any collection of elements, the simplest strategy is brute force. Here is the algorithm in pseudocode (I use an array for easy understanding):


//initialize maxValue to first element
maxValue = array[0];
//loop through the array and compare each element with the max value
for i = 1 to array.size - 1 do   
  if array[i] > maxValue  
  //if an element is greater than the current maxValue  
  //we make the maxValue the same with the current element
      maxValue = array[i];
return maxValue;


The strategy is to use a variable called maxValue to hold the greatest value we find. First initialize the maxValue to the first element. And as we go through the array, we change maxValue to whichever element that has higher value than maxValue. Keep doing that until we reach the end. By that time, maxValue holds the greatest value in the array.


Notice: The algorithm's time efficiency is O(n). This means that to find the max element in an array of 1,000 elements, the algorithm must do 1,000 comparisons :)


Got question / suggestion? Please post in the comment section below and I'll answer them as best as I can. Peace!

Make JavaScript-heavy webpage load faster

It is cleaner to put all your JavaScript files or scripts inside the "<header>" tag. However, browsers must interpret these scripts completely before going on to render the page content. And during interpretation, nothing is shown on the web page, offering no response to users' screen and making the website seem slow to load. 

Remember that most people will leave your page if it takes more than 5 seconds to show anything. Thus, include scripts in the body immediately before you need to use them. The browser will render whichever content available first and show it to users. It only have to interpret the scripts when it needs to. This will offer great feedback to users, letting them know your page is loading and making your page seems to load faster than it actually is! Here is a example of this technique: 
<html>  
  <head>  
    //we need this first so interpret this here <script type="text/javascript" src="xxx.js" />
  </head>
  <body>
     //Page content goes here
     //we need this later so interpret it later <script type="text/javascript" src="aaa.js" />  
  </body>
</html>


Warning: this doesn't mean that you can spread your scripts all over the page. Always try to externalize your scripts as much as possible and include the external files when you need them. Obey Object-Oriented Design :)
As always, if you have any question please feel free to post in the comment section below. 

Thursday, December 16, 2010

Display tags as literal strings in JavaScript

When using JavaScript statements such as document.write("<table>") to display HTML tags as literal strings, browsers will mistake that we want to insert the tags into the page structure instead of displaying them as text. For example:

<script type="text/javascript">
  //this won't display the text "<table>" and "</table>"
  document.write("<table>");  
  document.write("</table>");
</script>

The above script won't work. The screen will show nothing because the browser interprets the string as HTML table tags. To work around this, split the string that contains tags to be displayed into parts:

<script type="text/javascript">  
  document.write("<ta" + "ble>");  
  document.write("</tab" + "le>");
</script>

Happy coding and don't forget to comment :)

Tuesday, December 14, 2010

Things I Hate About Using SQLPLUS


1. No last-command macro
Do you remember how to can re-enter previous commands in Terminal / command line windows? By pressing the up or down arrow you can reuse the previous commands that you type. Well, guess what? That doesn't work in sqlplus which employs command line interface :( You have to retype the whole command even though it is a long one. Very irritating! For example:

INSERT INTO SECTION VALUES ('CS161', 1, 'W', '2011', 'Deborah K. Thomas', 'MTRF', to_timestamp('10:00:00', 'hh24:mi:ss'), to_timestamp('10:50:00', 'hh24:mi:ss'), to_date('01/03/2011', 'mm/dd/yyyy'), to_date('03/18/2011', 'mm/dd/yyyy'), 'BH123');
Re-type this if you want to reuse it!

2. Back key doesn't work!
To remove a character from a command, you must hit "Delete" key. That's fine but "Back" key that is supposed to do the same thing doesn't work. In MS Office, Terminal and any text editor, that's one of the functions of "Back" key. But oh no, sqlplus likes to be different. If you accidentally hit "Back" key, you will get a ton of gibberish instead of deleting the previous character!

3. No cursor movement
There is no way you can use the arrows to move your cursor from one place to another in sqlplus. For example, after typing this statement into sqlplus, I discovered that I missed a comma after "PRIMARY KEY":

CREATE TABLE COURSE ( Course_number VARCHAR(10) NOT NULL PRIMARY KEY Title VARCHAR(30) NOT NULL, Credit INT NOT NULL, Requirement VARCHAR(30) );
That means I have to delete everything up to that spot in order to insert a comma and then retype the just deleted words again :(

Stay tuned for my post about temporary solutions to these annoyances.