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

Wednesday, March 27, 2013

HTML5 canvas

Canvas is perhaps one of those features of HTML5 which caused a great deal of stir among the web developers. In simple sense, canvas tag allows you to specify a region on your document where you can draw stuff. One thing to be noted is we have to use some sort of a scripting language (usually JavaScript) to interact with canvas. For today's article I'll assume you know the basics of JavaScript.



Creating a Canvas Element

Creating a canvas element is quite simple:


<canvas height = "200" width = "200" id = "canvas1" ></canvas>
It is advised to always give a height and width to canvas element. A id is also necessary as there can be more than one canvas element in a single page.

The above code is actually as far as only HTML will take us, for functionalities of canvas we gotta use JavaScript as mentioned earlier. Please bear in mind any subsequent codes seen in this article must be written inside script tag or an external script file.

Understanding the Context

When we draw something on canvas, we actually retrieve the "context" of the canvas and put stuff on it. Broadly speaking, there are two types of context, 2d (mostly used) and 3d (still experimental). We will use the 2d context. Our first job is to identify our canvas element and create a handler to its 2d context. We do this by the following fragment:


 var canvas = document.getElementById('canvas1');
 var ctx = canvas.getContext('2d');
 
We are first creating a handler to our canvas element (recall it had the id 'canvas1'), then we are retrieving its 2d context through the function getContext().

Basic Canvas Properties

Remember we grabbed the context just on the previous section? Now we are going to set some of its properties. First let's have a look at three basic properties:

  • fillStyle:
    style to use when filling. We can specify CSS colors,gradients or patterns (defaults to black).

  • strokeStyle:
    style to use when filling. Constraints similar to that of fillStyle.

  • lineWidth:
    width of the lines drawn by our imaginary pen on canvas.

Drawing with colors and styles is a two step process. First one is to set the above properties. Other one is to perform the drawing operation i.e. calling the function which performs drawing.

Fill and Stroke

While dealing with canvas you'll find two versions of a function to create rectangles. these are fillRect and strokeRect ("Rect" standing for rectangle). What fill does is it creates the solid shape filled with the designated color/pattern, whereas stroke simply outlines the shape with that color. An example is presented shortly.

Before we append the following fragment to our code, let's have a look at the arguments that the fillRect or strokeRect takes:
x-coord, y-coord, width, height
The coordinates specify the position of upper-left corner of the rectangle, and width and height denotes the size of the rectangle. One reminder, the origin of the coordinate system is situated at the top-left corner of the canvas. Now we can append the following segment:


 ctx.fillStyle = 'tan';
 ctx.fillRect(10, 10, 100, 100);
  
 ctx.lineWidth = 5;
 ctx.strokeStyle = 'red';
 ctx.strokeRect(10 , 10, 100, 100);
 

First we chose the color tan and created a solid rectangle at (10, 10) having height and width of 100. Then we selected the lineWidth to be 5. Next we again selected a color, this time red; and stroked a rectangle at (10, 10) having similar dimensions as the previous rectangle. Notice although we have used colors as the property of fillStyle and such, we could have also used gradients or patterns, which is quite easily possible using CSS3.

Sample:
Your browser does not support the HTML5 canvas tag.

Sample code:
<canvas id="CanvasFill" width="120" height="120">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>
    var canvas = document.getElementById('CanvasFill');
    var ctx = canvas.getContext('2d');
    
    ctx.fillStyle = 'tan';
    ctx.fillRect(10, 10, 100, 100);

    ctx.lineWidth = 5;
    ctx.strokeStyle = 'red';
    ctx.strokeRect(10, 10, 100, 100);
    
</script>


Drawing Lines

For drawing a line we are going to use four functions: beginPath, moveTo, lineTo and stroke. The function beginPath tells that we are going to create path. We move the imaginary pen to a location through lineTo function. Notice that by "moving the pen" I mean picking the tip of the pen up and then placing it down again at the designated coordinate. The function lineTo instructs to draw a line starting from the current point to th point passed as parameter of lineTo. But the line is actually not drawn unless we call the stroke function. Let's have a look at the following fragment of code:


  ctx.lineWidth = 1;
  ctx.strokeStyle = 'black';
  ctx.beginPath();
  ctx.moveTo(10, 10);
  ctx.lineTo(110, 110);
  ctx.stroke();
  ctx.lineTo(200, 110);
  ctx.stroke();
 

We are setting the line width to be 1 and the color of the stroke to be black. Then we call the beginPath function. We move our imaginary pen to a point, in this case the point (10, 10). In the next line we instruct to create a line from (10, 10) to (110, 110). And finally to ensure the line is drawn, we call the stroke function. Notice that we created another line from the point where the previous line ended. If we wanted to draw a line from a different point we would have needed to call another moveTo function.

Sample:

Your browser does not support the HTML5 canvas tag.
Sample code:

<canvas id="CanvasStroke" width="200" height="150">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>
    var canvas = document.getElementById('CanvasStroke');
    var ctx = canvas.getContext('2d');
    
    ctx.lineWidth = 1;
    ctx.strokeStyle = 'black';
    ctx.beginPath();
    ctx.moveTo(10, 10);
    ctx.lineTo(110, 110);
    ctx.stroke();
    ctx.lineTo(200, 110);
    ctx.stroke();
    
</script>

Rendering Text

We can draw texts on canvas using fillText and strokeText functions. The arguments are:
text x-coord y-coord
Before calling these functions, we can also specify properties by assigning values to the font property of our context. The order in which these properties are assigned is:
font-style font-weight font-size font-face
The following code illustrates the complete method:


  ctx.strokeStyle = 'black';
  ctx.fillStyle = 'black';
  ctx.font = "normal normal 24px Tahoma";
  ctx.fillText("Hello world", 10, 140);
 
Sample:
Your browser does not support the HTML5 canvas tag.
Sample code:

<canvas id="CanvasText" width="200" height="100">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>
    var canvas = document.getElementById('CanvasText');
    var ctx = canvas.getContext('2d');
    
    ctx.strokeStyle = 'black';
    ctx.fillStyle = 'black';
    ctx.font = "normal normal 24px Tahoma";
    ctx.fillText("Hello world", 10, 40);
    
</script>



The canvas of HTML5 has a vast domain. In this article I've tried to point out just some of the basic ideas. From here I'd suggest you search the net for a bit more info. As always w3schools has a precise collection of more or less all the features of canvas. Besides this mozilla developer site can also turn out to be really helpful. Although at first canvas might seem a bit intimidating, it is actually quite a great tool to have at hand. Bottom line, this is by far the best light-weight option to create graphic objects on the fly.


Wednesday, February 20, 2013

How to Make Older Browsers Compatible with HTML5

In the past couple of years the web industry has seen a sudden boom in regards to HTML5. Although technically for the full specification to get approved we'll have to wait till the end of 2014, this is not stopping developers from writing codes in HTML5. Most, if not all, modern browsers have done a more or less good job in implementing the features of HTML5 (we all know which one doesn't!).

Unfortunately not all browsers have been able to implement all the new features that HTML5 is offering. So the developers often have to pay some extra care to make their code compatible with older browsers. In this article I'll try to point out some ways by which we can make older browsers compatible with HTML5. A little heads up though, this is about making browsers compatible with HTML5, not CSS3 (actually some aspects described are related to both, but our target is HTML5).

Getting to Know the Browsers

Before we get into making our code compatible and all that, we first need to have a clear idea on what actually the browsers can do. After all, what's the point of trying to teach someone what he/she already knows, right? Much to our advantage, there are some great sites which offer us considerable insight on browser features.

  • FindMeByIP
    On this site you'll find several charts where you can see a list of HTML5 features (and also CSS3) and info about which browser supports what feature. You can actually do it two ways, you can go to fmbip.com, in which case you'll get the info on the browser you are visiting the url by; or you can go to findmebyip.com/litmus, in which case you'll get a list of info on opera, chrome, mozilla, safari and IE versions 6, 7, 8, 9.
  • CanIUse
    This site also has a comprehensive listing of compatibility info (color coded, always helps). You can search for a particular feature or just skim through all that are listed. This is actually one of the sites I have been frequently visiting since I first started coding in HTML5 and CSS3.
  • HTML5Please
    This site is a bit different than the previous two. It does not contain a pin pointed list of what each browser can do, rather it gives us suggestions about what measures we should take regarding various features: whether we should totally avoid, use backup (i.e. polyfills, more on this later), use with caution or freely use a particular feature. According to the front page of this site, the recommendations are based on the experience of web developers. So it can turn out to be really handy in practical usage.
  • Browsershots
    Browsershots makes screenshots of your web design in different operating systems and browsers. Not really informative, but to have a quick glimpse of what our page will look in different browsers, quite an impressive site.
  • Spoon.net
    I personally think this is an awesome site. The Spoon.net Browser Sandbox provides us a method of cross-browser testing. All we have to do is just click run for any browser from the given list to launch it instantly. By the way you have to have an account to use its feature, and guess what, account creation is free!

Now that we know we can thoroughly investigate abilities of various browsers, let's get them compatible with HTML5. One thing that you'll see in common in most of these methods is the use of JavaScript. Let's list our options first and then we'll start cracking them one by one.

Ways to Make Older Browsers HTML5 Compatible

  • Pure ol' JavaScript
  • html5shiv (also known as html5shim)
  • modernizr
  • HTML5 Boilerplate
  • Google Chrome Frame (especially for IE)

Before I proceed further, I'd like to make one thing very clear: using the above mentioned ways does not make our browser all of a sudden capable of implementing all the features that HTML5 offers, in most cases it just makes the browser recognize that there is a tag with a specified name. For example, using the first 3 ways you can make older browsers know that there is a tag named 'canvas', but you can't really perform actions which canvas really offers (note: I am saying HTML5 Boilerplate supports canvas because it actually makes IE render web pages using Google Chrome Frame, which happens to support canvas).

Custom JavaScript

This is the elementary way of letting the browser know what new tags we are going to use if it is not familiar with them already. Say for example we want to use the tag "header". This is a tag which IE versions prior to 9 don't understand. So here's what we can do:

   <!--[if lt IE 9]>
    <script type="text/javascript">
      document.createElement("header");
    </script>
   <![endif]-->
  
It goes without saying that we have to place the piece of code between the "head" tags. The code snippet is quite self explanatory; even then, let's have a quick look at it. At the very first line we are starting a commented section, which basically says if the browser is less than IE version 9, interpret the following code; otherwise ignore what's in between the "if - endif" tags. Inside the script tags, we just have to call the createElement() function with the appropriate parameter. As an instance, if we also wanted to use "nav" tag we would have added the statement document.createElement("nav") in between script tags.

html5shiv

As stated before, it's also known as html5shim. So what is a shim? It is an application compatibility workaround (for those of you who have already googled it, yup, I took it from wikipedia). html5shim is one of the most popular polyfills (remember I stated the term "polyfill" previously? here it comes!). Paul Irish gave a simple definition of polyfills. If you are wondering who is Paul Irish, just know that he is sort of a front-end wizard in web industry. According to him polyfill is “a shim that mimics a future API, providing fallback functionality to older browsers”. You can download html5shiv here.

In case you are interested in technicalities, html5shiv sort of works by following the first method described i.e. creating element through JavaScript. After you download it, all you need to do is include the following snippet inside "head" tag:

   <!--[if lt IE 9]>
    <script src="dist/html5shiv.js"></script>
   <![endif]-->
  

modernizr

A really worthy name, it does make us modern (at least in regards to front-end development, that's for sure!). The best place to learn about modernizr is its official site. But don't worry; I'm not leaving you empty-handed. In short, what modernizr does is perform feature detection first. Note that I said "feature" detection, not "browser" detection. That basically means it finds out what our browser can do, not what browsers we are using. It then attaches necessary classes to our "html" tag. Say for example our browser does not support "canvas" tag, so a class named "no-canvas" will be added to our "html" tag. In the opposite case the class added would have been "canvas". So what do we do to use modernizr? Same as before, we download a copy of modernizr.js (you can find a link in the official site) and add the following code inside "head" tag:

   <script src="js/modernizr.js"></script>
  
It's worth noting that we can use modernizr to detect feature within our JavaScript, such as:

   if(Modernizr.geolocation){
    
   }
  

HTML5 Boilerplate

This is what I'd like to say is the ultimate blueprint. The package contains modernizr and jquery library. It also has normalize.css (I left out normalize from previous descriptions as it is related to CSS). You can find a link to download html5boilerplate from its website. Once downloaded, if you explore the folder you'll find all the files I've previously mentioned. The index.html is where your html goes. To simply define, this is a template for implementing HTML5.

Google Chrome Frame (Abbreviated as GCF)

For those of you who are really frustrated with IE, I saved the best for the last. Google Chrome Frame is simply a plug-in for IE which lets it render a webpage the same way google chrome would. Of course the downside is you can't use the features not supported by google chrome, but trust me, the amount of such features is negligible compared to IE. As far as I know, chrome ranks the second in regards to adopting HTML5 features (Maxthon being first). You can check the current standings from the site html5test. We basically have to do two things to make a page be displayed using Google Chrome Frame in IE.

Firstly, we have to make sure that the viewer's IE already has the plug-in installed. Frankly speaking, there is no way to force the user to install GCF, but at least we can prompt the user to install it. The developer's site chromium.org gives a way to use a JavaScript file named "CFInstall.js" which exactly does that. You can find an example of using "CFInstall.js" here. For your convenience I'm presenting the code below:

<html>

<body>
 <script type="text/javascript" 
 src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"></script>

  <style>
  /* 
  CSS rules to use for styling the overlay:
   .chromeFrameOverlayContent
   .chromeFrameOverlayContent iframe
   .chromeFrameOverlayCloseBar
   .chromeFrameOverlayUnderlay
   */
   </style> 

   <script>

   // You may want to place these lines inside an onload handler
   CFInstall.check({
       mode: "overlay",
       destination: "http://www.waikiki.com"
            });
   </script>
   </body>
   </html>
  
Secondly, we have to give instructions to our page to use GCF. We do this by adding the following simple meta inside "head" tag:
   <meta http-equiv="X-UA-Compatible" content="chrome=1">
  

HTML5 Cross Browser Polyfills

Remember I said taking certain measures as stated above will not actually make our browser able to use all the features provided by HTML5, but rather make our browser knowledgeable on the fact that there are certain tags? For those of you who became heartbroken, take a look at this site.. It provides a list of fallback options for HTML5 features.

Before I conclude I'd like to mention one thing. HTML5 is gaining popularity at a very high rate, and the browsers are also catching up nicely. After a few years I think there won't be the concept of making browsers "compatible with HTML5" (and sadly my so thoughtful article will become obsolete). But till then, we certainly have to keep our eyes open and take necessary measures.