Você está na página 1de 36

HTML5-An overview

This site Learn HTML5.info aims at providing a better exposure about HTML5 to the users .For more than a decade there has been no prominent updation in the HTML4 version .But once HTML5 was released a couple of years back it has been a hot topic for a while.Many interesting features have been added in the HTML5.for years users and the browsers have to depend on 3rd party plugins to play audio and video but now HTML5 has given a solution for that.Let us see some of the prominent and intreasting features of HTML5 in this tutorial HTML5 an introduction . Structural Tags in HTML5 HTML5 vs Flash Tags in html -part1(<a> ,<address> ,<audio>..<fieldset>) Tags in html -part2(<figure>,<form>,<h1>to<h6>,<i>..<source>) Tags in html -part3(<strong>,<style>,<sub>,<table>.<video>) 5 key features of HTML5 HTML5 Canvas Element . Drawing using Canvas Element. Using path in canvas elements. Canvas complex example. Applying styles and colors using canvas. canvas element transformations. translating a canvas feature. Rotating canvas transformation method. Scaling canvas transformation method. Transform canvas transformation method. Clipping paths.

HTML5 an Introduction
An OverView
HTML is not a programming language, but rather a markup language. It is a formatting language that programmers and developers use to create documents on the Web. It has been roughly 10 years we have been using the HTML -4 versions. Even though XHTML was released during the last decade by W3C HTML4 did not see any major ground breaking changes. HTML 5 has been a hot topic now for a while ever since it was first released in 2009. The HTML5 work stems from the WHATWG (Web Hypertext Application Technology Working Group).

New Features in HTML5


The latest edition HTML5 has enhanced features for programmers such as <video>, <audio> and <canvas> elements. These features have been implemented in HTML5 to include multimedia and graphical content on the web without relying on external plugins and APIs to run audio, video and all these kind of stuffs. HTML 5 recognizes that Web pages have a structure, just like books have a structure or other XML documents. In general, Web pages have navigation, body content, and sidebar content plus headers, footers, and other features. And HTML 5 has created tags to support those elements of the page. Other new elements that find place in this new version of HTML includes <section>, <article>, <header>, and <nav> tags these tags have been included to enrich the semantic content of documents, *<section> - to define page section. *<header> - defines page header. *<footer> - defines page footer. *<nav> - defines page navigation. *<article> defines primary content on a page. *<aside> defines extra content like a sidebar on a page. *<figure> - defines images that annotates an article. other features like content Editing, cross-Document Messaging ,Web2.0 ,client side storage are also included in this HTML5 version.Also in this new version of HTML the tags and elements that were less usable in the previous versions are removed .

Structural Tags in HTML5


As discussed in the (intro)previous post the HTML5 has added many interesting features and tags that would be very helpful for structuring a webpage. Some of these tags include <header>, <nav>, <article>, <section>, <aside>, <footer>. You can use these tags instead of more common DIV layers we used till HTML4 (for example: <div id=header>. . .</div>). Lets us discuss these new structural tags in HTML5.

<header> tag
The <header> tag is a headline or grouping of headlines it specifies an introduction, or a group of navigation elements for the document. Headers can contain headings, subheadings, version information, navigational controls, etc.

<nav> tag
The HTML < nav> tag is used to declare a navigational section of HTML document .It generally consists of list of links.

<article> Tag
The HTML <article> tag is used to represent an article .More specifically the content within the <article> tag and it is independent from the other content in the site and can stand alone.

<section >tag
The HTML <section> tag is used to represent a section within an article. Eg. A homepage of a particular sales site can have many sections like a section to introduce it, a section describing its nature of work and a section to display testimonials by the clents. In such a scenario < section>tags can be used.

<aside > Tag


The HTML <aside> tag would be used to represent the content that are related to the surrounding content that has to be placed within an article.You can mostly see them in sidebars in many websites.

<footer> Tag

This footer tag is used to define footer of a HTML document.Normally footers contain information like terms of use ,privacy policy , information about author <pre><!DOCTYPE html> <html> <head> <title>strutural </title> </head> <body> <header> <h1>Structural Tags</h1> </header> <nav> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> </nav> <section> <article> <header> <h1>Structural Tags in HTML5</a></h1> </header> <section> <p>HTML5 has added many interesting features and tags</p> </section> </article> </section> <footer> <p>Copyright QualityPointTechnologies</p> </footer> </body> </html>

HTML5 vs Flash
Today most of the browsers use a flash plugin to play the videos.This works pretty well but Flash unfortunately requires a lot of computing power.This would be an issue if the system has a low end configuration Hence the new web standard HTML5 is trying to change that. HTML5 has been designed with audio and video codecs which take less processing power its equivalent Flash player which rules the browsers audio and video plugin.As with most new technologies, things are not always clearcut. HTML5 is the largest ever opensource project undertaken by W3C.Hence we can expect some terrific improvements in processing efficiency from HTML5,it should not be assumed that it will completely replace Flash or even have a significant impact,especially on rich web content. Flash still has many advantages such as. Better sub pixel resolution and anti aliasing

Its good excellent developer tools (far more extensive than HTML5) Flash has a vast array of good looking and impactful fonts At this point, graphic artists and game developers still feel that flash is the best. Though they might certainly like the idea of being able to operate with less computing overhead, they want to get the most control and ability to generate outstanding results that flash would provide them while HTML5 may or maynot deliver. However for many simpler video playback application such as in YouTube,metacafe HTML5 has the ability to quickly surpass Flash as the video/audio player of choice in browsers. At this point, the development of the YouTube HTML5 supported player is still in its early phases and a lot more tweaking and refinement must be done. Right now It needs more support to work properly with other browsers and extensive testing to work out instability and incompatibility issues.However since its on an open platform, there are many people working through these issues so it is just a matter of time. But many developers feel that this process might take years as there are still many issues to work out. As few specifications stated in HTML5 are controversial. And another bottleneck is HTML5 is not compatible with all browsers and many users are resistant to changing to another browser. As far as an average user is con concerned if a browser works well he doesnt bother to switch over to new technology or a new browser in such a scenario HTML5 has a daunting task ahead to replace the position of flash. For example, Internet Explorer is largely criticized for its instability and security flaws. Yet many people steadfastly hold on that browser and are very reluctant to change to something like Firefox or Chrome. So be aware that even with the potential efficiencies which HTML5 can bring, dont expect rapid deployment or changes away from Flash.

Tags in HTML5
The Doctype
The doctype declaration is not an HTML tag. This tag is used for specifying the language and version the document is using. The <!DOCTYPE> tag does not have an end tag and it is not case sensitive too. The HTML5 specification recommends that all documents should have <!DOCTYPE> header at the top of it.

Example
<!DOCTYPE> <html>

<head> <title>Using Doctype</title> </head> <body> <p>Hello world!</p> </body> </html>

<a> tag
This <a > tag is used to link another page from a webpage. The attribute target in <a> tag can be used to specify if the new page should open in a new tab or in a new window. <a href="http://learnwebdevelopment.info">learn web development</a> Attributes : *href specifies the URL of a page that the links go to *target species the mode the webpage should open. *Rel -This establishes a relationship between current and the destination document URL.

<address> tag
HTML5 address tag is used to mention an address in a document or in a section of a document. <address>This document was written by: <a href="mailto:homer@example.com">Homer Simpson</address>

<area > tag


HTML area tag is used to define some areas in an image map. You can tag a particular area in an image to be tagged and when the mouse moves over the particular part of the image the information that was coded will be displayed.

<audio > tag


This is an interesting feature that have been included in HTML5 .Till previous versions we need to depend on 3rd party plug-in like flash player to play audios in a webpage. But HTML5 has an inbuilt feature for that <audio > tag in HTML5 can be used to play audio in a webpage. <audio src=" music path "></audio>

<b> tag
This tag is used to specify a text in bold. Added to this one can use headers like <h1> , <h2> , <h3> , <h4> . <b>bold</b> text.

<base> tag
<base> tag is used to specify the base URL. Once a base URL is set on top of the page all the subsequent links that are used in that page will use the base URL as the starting point.<base> tag should be placed in the head section. <html> <base href="http://www.onepass.biz/" target="_blank" /> </head> <body> <p>Learn about <a href="2011/07/onepass-to-search-engines/ ">search engines </a></p> </body> </html>

<bdo> tag
This <bdo> tag is used to change the text direction . <bdo dir="rtl">LearnHTML5.info</bdo> Attributes: *rtl ltr indicates the direction of the text.

<body> tag
This tag is used indicate main content section .This is normally placed between the </head> and </html> tags. <!DOCTYPE HTML> <html> <head> <title>HTML body tag</title> </head> <body style="background-color:blue"> <p>LearnHtml5.info</p> </body> </html>

<br> tag
The HTML <br> tag is used to break a line.

Example :
<!DOCTYPE HTML> <html> <body> <p>Try hard <br /> Till the goal is not reached.</p> </body> </html>

<button> tag
This is used to create button controls in webform.Inside a button one can put text or images to make the purpose understandable to the users. <!DOCTYPE HTML> <html> <body> <button type="button">Click Me!</button> </body> </html> Attributes: *Autofocus : Indicates that the button should have the focus when the page loads. *Form :specifies which form the button belongs. *Formaction : specifies where the data should be send once the form is submitted. *Formmethod : specifies the method the data to be send .There are two modee 1)get 2)post

<canvas> tag
Canvas tag is used to display graphics.The <canvas> tag is just a container actually a script should be used to paint graphics. <!DOCTYPE HTML> <html> <body> <canvas id="myCanvas"></canvas> <script type="text/javascript"> var canvas=document.getElementById('myCanvas'); var ctx=canvas.getContext('2d'); ctx.fillStyle='#FF0000'; ctx.fillRect(0,0,80,100); </script> </body> </html>

<caption> tag
It is used in along with the <table> tag to display the table title.

Example
<!DOCTYPE HTML> <html><head> </head> <body> <table> <caption>Monthly savings</caption> <tr> <th>Name</th> <th>Roll Number</th> </tr>

<tr> <td>shawn</td> <td>4</td> </tr> <tr> <td>jim</td> <td>14</td> </tr> </table> </body> </html>

<cite> tag
It is used to represent title of book or sometext to distinguish from the normal text. <!DOCTYPE HTML> <html> <body> <cite>Citation</cite> </body></html>

<Col> tag
The HTML <col> tag is used for specifying column properties for each column within a colgroup.

<colgroup> tag
HTML <colgroup> is used to specify properties for a group of columns within a table. <!DOCTYPE HTML> <html> <body> <table border="1"> <colgroup span="2" style="background-color:red"> <col width="50"></col> <col width="100"></col> </colgroup> <tr> <td>col 1</td> <td>col 2</td> <td>col 3</td> </tr></table></body</html> Attribute: *Span : species the number of columns that the attribute value should be extended.

<command> tag
The HTML <command> tag is used for specifying a command a user can invoke. <!DOCTYPE HTML> <html><body> <menu><command onclick="alert(Welcome')">Click </command>

</menu></body></html> Attributes: *Checked : Defines if the command is checked or not.

<datalist> tag
The <datalist> tag defines a list of options. Use this element together with the input element, to define which values the input element can have. Use the input elements list attribute to bind it together with a datalist. <!DOCTYPE HTML> <html><body> <input list="cars" /> <datalist id="cars"> <option value="BMW"> <option value="Ford"> <option value="Volvo"> </datalist> </body> </html>

<dd> tag
The HTML <dd> tag is used for specifying a definition description in a definition list. <!DOCTYPE HTML> <html> <body> <dl> <dt>learnhtml5.info</dt> <dd>A complete guide to learn HTML5</dd> </dl></body> </html>

<del> tag
HTML <del> tag is used for markup of deleted text.Browsers normally strike out the text that is tagged withdeland underline the inserted text. <!DOCTYPE HTML> <html> <body> <p>My favorite car is <del>skoda</del> <ins>Benz</ins>!</p> </body></html>

<details> tag The HTML <details> tag specifies additional details that the user can view or hide on demand.
<!DOCTYPE HTML> <html><body>

<details> <summary>Copyright 2011</summary> <p>All pages and graphics on this web site are the property QualityPoint Technologies.</p> </details> </body> </html>

<dfn> Tag
<dfn> tag is used for indicating a definition.

Example :
<!DOCTYPE HTML> <html> <body> <dfn>Definition term</dfn><br /> </body> </html>

<div> tag The HTML <div> tag is used for defining a section of your document. With the<div> tag, you can
group large sections of HTML elements together and format them with CSS. <!DOCTYPE HTML> <html> <body> <div style="color:#FF0000"> <h3>This is a learnhtml5.info</h3> <p>You are learning HTML.</p> </div> </body> </html>

<em> tag
The HTML <em> tag is used for indicating emphasis. The em tag surrounds the word/term being emphasised. <!DOCTYPE HTML> <html> <body> <em>Emphasized text</em><br /> </body> </html>

<embed> tag
The HTML <embed> tag is used for embedding an external application or interactive content into an HTML document.

Sample
<!DOCTYPE HTML> <html> <body> <embed src="path" /> </body> </html>

<fieldset> tag
This is used to group related information. <!DOCTYPE HTML> <html> <body> <form> <fieldset> <legend>Details</legend> Name: <input type="text" /><br /> Email: <input type="text" /><br /> Date of birth: <input type="text" /> </fieldset></form></body> </html>

Tags in HTML5-part2
<figure> tag
The HTML <figure> tag is used for annotating illustrations, diagrams, photos, code listings, etc.You can use the <figure> element to associate a caption together with some embedded content, such as a graphic or video.

<form> tag
The <form> tag is used to create an HTML form for user input.The form element contains one or more form elements like: button, input, keygen, object, output, select, textarea and more.

Example
<!DOCTYPE HTML> <html><body> <form action="form_action.asp"> First name: <input type="text" name="fname" value="david" /><br /> Last name:<input type="text" name="lname" value="Attenborough" /> <br /> <input type="submit" value="Submit" /> </form> <p>Click the "Submit" button and the input will be sent to a page on the server called "form_action.asp".</p></body> </html>

<h1> to <h6>
These levels from h1 to h6 specify the text size from 1 to 6. <!DOCTYPE HTML> <html> <body> <h1>This is header 1</h1> <h2>This is header 2</h2> <h3>This is header 3</h3> <h4>This is header 4</h4> <h5>This is header 5</h5> <h6>This is header 6</h6> </body> </html>

<i> tag
The HTML <i> tag is render a text in italic. It is normally used to differentiate a part of a text from others. <p>check out <i>learnwebdevelopment.info</i>, to know more about web designing.</p>

<iframe> tag
iframe tag is used to specify and create an inline frame that contains another document or a webpage <iframe src="<a href="http://learnwebdevelopment.info/">http://learnwebdevelopment.info/</a>"></iframe>

<img>tag
<img> is used to embed an image to our document. <img src="hotsunday.gif" alt="Hot Sunday" /> Attributes: *Alt : specifies an alternative name to that image. *Src : specifies the source of the image. *Height : specifies the height of the image. *Width : specifies the width of the image.

<input> tag The HTML <input> tag is used within a form to declare an input element a control that allows
the user to input data. <form action="form_action.asp" method="get"> First name: <input type="text" name="fname" /><br /> Last name: <input type="text" name="lname" /><br /> <input type="submit" value="Submit" /> </form>

<ins> tag
This is used to markup a text and to highlight it from other text. <p>I can visit <del>very</del> <ins>www.learnwebdevelopment.info</ins> to gain insight knowledge in webdevelopment.</p>

<kbd> tag
This is another kind of text formatter to distinguish the text from the rest. <kbd>Keyboard text</kbd>

<Keygen> tag The HTML <keygen> tag is used for generating a key pair. When the controls form is submitted,
the private key is stored in the local keystore, and the public key is packaged and sent to the server.

<label> tag
<label> tag defines a label for the input element. When a label is used in a radiobutton or a checkbox the text that is associated with a particular input element can be triggered to invoke the input element. <form> <label for="banana"> banana </label> <input type="radio" name="sex" id=" banana " /> <br /> <label for="Apple"> Apple </label> <input type="radio" name="sex" id=" Apple " /> </form>

<legend> tag
The HTML <legend> tag is used for providing a title or explanatory caption for the rest of the contents of the legend elements parent element. <form> <fieldset> <legend>Personalia:</legend> Name: <input type="text" size="30" /><br /> Email: <input type="text" size="30" /><br /> Date of birth: <input type="text" size="10" /> </fieldset> </form>

<li> tag
<li> tag defines a list of items.

<OL> tag
Ordered list here the elements that are grouped under are prefixed with numbers ..like 1 ,2 ,3

<ol> <li>Cats</li> <li>Dogs</li> </ol> We can also set the starting value using the attribute start <ol> <li value="5">Cats</li> <li>Dogs</li> </ol>

<UL> tag
In unordered list bullets can be used to index an element. <ul> <li>Cats</li> <li>Dogs</li> </ul>

<link> tags
<link> tags are mostly in stylesheet and are used connect document to an external resource. <head> <link rel="stylesheet" type="text/css" href="mystyle.css" /> </head>

<mark> tag
The HTML <mark> tag is used for indicating text as marked or highlighted for reference purposes, due to its relevance in another context. <p>HTML5 supports <mark>audio</mark> and <mark>video</mark> which was not present in the previous version.</p>

<menu> tag
The HTML menu tag is used for specifying a list of commands. <menu> <li>Command 1</li> <li>Command 2</li> <li>Command 3</li> </menu>

<meta> tag
<meta> tag is used to add meta description to the document. <head> <meta name="description" content="Free Web tutorials" /> <meta name="keywords" content="HTML,CSS,XML,JavaScript" />

<meta name="author" content="Stle Refsnes" /> <meta charset="UTF-8" /> </head>

<meter> tag
The HTML <meter> tag is used for indicating a scalar measurement within a known range, or a fractional value. Also known as a gauge, usage could include displaying disk usage, the amount raised during fundraising activities, or the relevance of a search query result. <meter value="2" min="0" max="10">2 out of 10</meter><br /> <meter value="0.6">60%</meter>

<nav > tag


The HTML <nav> tag is used for declaring a navigational section of the HTML document. <nav> <a href="/css/" target="_blank">CSS</a> | <a href="/html/" target="_blank">HTML</a> | <a href="/javascript/" target="_blank">JavaScript</a> | <a href="/sql/tutorial/" target="_blank">SQL</a> </nav>

<P> tag
<p> tag is used to define a paragraph. <p>This paragraph is defined using the HTML p tag.</p>

<param> tag
This tag is used to pass parameter to embedded object. <object data="song.mp3"> <param name="autoplay" value="false" /> </object>

<pre> tag
The <pre> tag defines preformatted text.The same format is displayed in the webpage too. <pre> This text would be Displayed in the same Way as how it is formatted Here.</pre>

<progress> tab
<progress> tab is used to represent the progress of a task using task bar. The files downloading progress: <progress value="22" max="100"> </progress>

<q> tag
<q> tag is used to apply quotes to a text. <p> u can learn webdevelopment from <q>webdevelopment.info</q></p>

<ruby> tag
The HTML <ruby> tag is used for specifying Ruby annotations, which is used in East Asian typography.

<samp> tag
The HTML <samp> tag is used for indicating sample output from a computer program, script etc. The samp tag surrounds the sample word/phrase.

<script> tag
The HTML <script> tag is used for declaring a script (such as JavaScript) within your HTML document. <script type="text/javascript"> document.write("Hello World!") </script>

<select> tag
The HTML <select> tag is used for defining a select list. <select> <option value ="HTML">HTML</option> <option value ="CSS">CSS</option> <option value ="PHP" selected>PHP</option> </select>

<small > tag


<small> tag is used to specify small print. <p><small> Copyright QualityPoint Technologies</small></p>

<source> tag
The HTML <source> tag is used to specify multiple media resources on media elements (such as <audio> and <video>). <audio controls="controls"> <source src="song.ogg" type="audio/ogg" /> </audio>

Tags in HTML5-part3
<strong> tag
It is one kind of text formatter used to bold the text. This is <strong>important</strong>.

<style> tag
The HTML <style> tag is used for declaring style sheets within your HTML document. <style type="text/css"> h1 {color:red} p {color:blue} </style>

<sub> tag
The HTML sub tag is used for subscript text <p>The HTML sub tag is used for <sub>subscript text</sub></p>.

<summary> tag
The HTML <summary> tag specifies a summary/caption that can be used in conjunction with the HTML5 <details> tag. This summary/caption can be clicked on to expand/collapse the details as required. <details> <summary>company</summary> <p>QualityPoint Technologies</p> </details>

<table> tag
The HTML <table> tag is used for defining a table. The <table> tag contains other tags that define the structure of the table.

<td> tag :

Table Definition used to define table header.

<tr> tag
Table row Used to specify the start and end of each row in a table. <table border = "1"> <tr> <td>Name </td> <td>Roll</td> </tr> </table>

<textarea> tag
The HTML textarea element allows the user to enter more than one line in the textbox. The inputbox should be appropriately coded with the height and width of the textbox. <textarea rows="5" cols="25">Enter your view s here.</textarea>

<tfoot> tag
<tfoot> tag is used to group the footer content in the HTML table.They should be used along with the <thead> and < tbody> .

<thead> tag
<thead> tag is used to group the header elements in the HTML table. <table> <thead> <tr> <th>Name</th> <th>Roll Nimber</th> </tr> </thead> <tfoot> <tr> <td>Sam</td> <td15</td> </tr> </tfoot> <tbody> <tr> <td>Anderson</td> <td>48</td> </tr> </tbody> </table>

<time> tag
The HTML <time> tag is used for declaring the date and/or time within an HTML document.

<p>On Saturdays, we open at <time>09:00</time>.</p>

<title> tag
The HTML <title> tag is used for declaring the title, or name, of the HTML document.This would normally appear at the browsers title bar. <html> <head> <title>Learn HTML5</title> </head>

<video> tag
The HTML5 <video> tag is used to specify video on an HTML document. For example, you could embed a music video on your web page for your visitors to listen to and watch. <video src=" video source " width="300" height="150" controls>

5 key features of HTML5


HTML5, the latest version of HTML series offers a number of unique features that will change the way websites and users interact between them.Even though HTML5 has got many features it has got 5 important features which revolutionize the way users view websites and clearly distinguish them from the previous versions. HTML5 will significantly change the way websites are designed.Search engines will get access to tap into a richer source of information. Already HTLM5 has found a place in ipods ,ipads and google andriod mobile phones.Let me just showcase the major features of HTML5.some of the key elements are

1)Video elements: Designers can now build web pages without depending on third-party
proprietary plug-in software like Flash. YouTube is now experimenting with using HTML 5 to display video. Built in video controls makes the feature more attractive and easy to use.If this feature comes into effect this would be a perfect replacement to flash plugins.

2.Application cache:you can now store web apps much like emails locally. Google has
already made use of this feature replacing its Google Gears mail client with HTML 5. Google Wave also uses HTML5.

3.Canvas for Images:The canvas element that comes with HTML5 lets a developer to
manipulate graphics and photos enabling easy rendering of images.Designers no longer need to depend on intermediate technologies like jQuery. This will help saving development time and effort.

4.Geolocation: The HTML5 Geolocation feature enables location identification using various
geo location technologies like GPS (Global Positioning system), IP address, RFID (Radio frequency

ID),Wi-Fi,Bluetooth MAC address and GSM/CDMA cell IDs. The system is bound by privacy regulations and needs to be authorized by individuals before it can be utilized.

5.Web workers: This feature enables a web application to execute complex tasks
independently without interfering with the performance of a webpage in real-time. These are the 5 features that clearly says that HTML5 has a huge role to play in the near future.

HTML5 canvas element


The HTML5 Canvas element is an HTML tag similar to the <div>, <a>, or <table> tag, with the exception that its contents are rendered with JavaScript. In other words, in order to leverage the HTML5 Canvas, youll need to place the canvas tag somewhere inside your HTML, create an initializer JavaScript function that accesses the canvas tag once the page loads, and then utilize the HTML5 Canvas API to draw your visualizations. <canvas id="myCanvas"></canvas>

HTML5 Canvas Template


<!DOCTYPE HTML> <html> <head> <script> window.onload = function(){ var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); // do stuff here }; </script> </head> <body> <canvas id="myCanvas" width="578" height="200"> </canvas> </body> </html>

HTML5 Canvas Element Explanation


The code above will be the base template for all of your future HTML5 Canvas projects. We can define the height and width of the canvas tag using the height and width attributes, just like we would with any other HTML tag. Inside the initializer function we can access the canvas DOM object by its id, and then get a 2-d context using the getContext() method.

Drawing using Canvas Element.


Here is a simple example using canvas that can be used to draw two intersecting rectangles

<script type="text/javascript">// <![CDATA[ function draw() { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.fillStyle = "rgb200,0,0)"; ctx.fillRect (55, 10, 55, 50); ctx.fillStyle = "rgba(0, 0, 200, 0.5)"; ctx.fillRect (30, 30, 20, 50); } // ]]></script> <canvas id="canvas" width="300" height="300"></canvas> The draw function gets the canvas element, then obtains the 2d context. The ctx object can then be used to actually render to the canvas. The example simply fills two rectangles, by setting fillStyle to two different colors using CSS color specifications and calling fillRect. The second fillStyle uses rgba() to specify an alpha value along with the color. The fillRect, strokeRect, and clearRect calls render a filled, outlined, or clear rectangle. To render more complex shapes, paths are used.

Canvas Examples -Using Paths


The beginPath function starts a new path, and moveTo, lineTo, arcTo, arc, and similar methods are used to add segments to the path. The path can be closed using closePath. Once a path is created,

you can use fill or stroke to render the path to the canvas.

<html> <head> <script type="application/javascript"> function draw() { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.fillStyle = "red"; ctx.beginPath(); ctx.moveTo(30, 30); ctx.lineTo(150, 150); // was: ctx.quadraticCurveTo(60, 70, 70, 150); which is wrong. ctx.bezierCurveTo(60, 70, 60, 70, 70, 150); // <- this is right formula for the image on the right -> ctx.lineTo(30, 30); ctx.fill(); } </script> </head> <body onload="draw()"> <canvas id="canvas" width="300" height="300"></canvas> </body> </html> Calling fill() or stroke() causes the current path to be used. To be filled or stroked again, the path must be recreated.

A complex canvas example


We saw about canvas using path and also using rectangles in this example we will see how to combine them to form a complex and at the same time an interesting composition.

<html> <head> <script type="application/javascript"> function drawBowtie(ctx, fillStyle) { ctx.fillStyle = "rgba(200,200,200,0.3)"; ctx.fillRect(-30, -30, 60, 60); ctx.fillStyle = fillStyle; ctx.globalAlpha = 1.0; ctx.beginPath(); ctx.moveTo(25, 25); ctx.lineTo(-25, -25); ctx.lineTo(25, -25); ctx.lineTo(-25, 25); ctx.closePath(); ctx.fill(); } function dot(ctx) { ctx.save(); ctx.fillStyle = "black"; ctx.fillRect(-2, -2, 4, 4); ctx.restore(); } function draw() { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); // note that all other translates are relative to this // one ctx.translate(45, 45); ctx.save(); //ctx.translate(0, 0); // unnecessary drawBowtie(ctx, "red"); dot(ctx); ctx.restore();

ctx.save(); ctx.translate(85, 0); ctx.rotate(45 * Math.PI / 180); drawBowtie(ctx, "green"); dot(ctx); ctx.restore(); ctx.save(); ctx.translate(0, 85); ctx.rotate(135 * Math.PI / 180); drawBowtie(ctx, "blue"); dot(ctx); ctx.restore(); ctx.save(); ctx.translate(85, 85); ctx.rotate(90 * Math.PI / 180); drawBowtie(ctx, "yellow"); dot(ctx); ctx.restore(); } </script> </head> <body onload="draw()"> <canvas id="canvas" width="300" height="300"></canvas> </body> </html> In the above example we can find two methods drawbowtie and dot both these methods are called 4 times each .And the calls like translate() ,rotate() are used to set transformation matrix which in turn positions the dot and the bowtie .dot function is used to place the small black square at (0,0) .That dot is moved around by the transformation matrix .drawBowtie will create a very simple bowtie path using the passed-in fill style. The functions save() and restore() are used to set the original canvas state.This rotation always occur around the current origin.Thus a translate() rotate() translate() sequence will yield different results than a translate() translate() rotate() series of calls.

Applying styles and colors using canvas


Canvas elements can be used to give colors also we discussed about various drawing functionalities in canvas element .In this post we shall discuss about the coloring features in canvas element . Colors There are two properties that canvas element provide us to apply colors to shapes fillStyle = color strokeStyle = color strokeStyle parameter helps in defining the outline color of the shape. fillstyle parameter helps in coloring inside the shape.

Any CSS color code can be used here. //these all set the fillStyle to 'orange' ctx.fillStyle = "orange"; ctx.fillStyle = "#FFA500"; ctx.fillStyle = "rgb(255,165,0)"; ctx.fillStyle = "rgba(255,165,0,1)";

A fillStyle example
In the following fill style example we can find that two loops run to form a grid of rectangles each grid form s a unique color combination The values of I and J runs to form various color codes .

function draw() { var ctx = document.getElementById('canvas').getContext('2d'); for (var i=0;i<6;i++){ for (var j=0;j<6;j++){ ctx.fillStyle = 'rgb(' + Math.floor(255-42.5*i) + ',' + Math.floor(255-42.5*j) + ',0)'; ctx.fillRect(j*25,i*25,25,25); } } }

A strokeStyle example
This strokestyle example is same as the above but with the difference it shows in the property.

function draw() { var ctx = document.getElementById('canvas').getContext('2d'); for (var i=0;i<6;i++){ for (var j=0;j<6;j++){

ctx.strokeStyle = 'rgb(0,' + Math.floor(255-42.5*i) + ',' + Math.floor(255-42.5*j) + ')'; ctx.beginPath(); ctx.arc(12.5+j*25,12.5+i*25,10,0,Math.PI*2,true); ctx.stroke(); } } }

Canvas Element transformations


In the previous posts we discussed about the using images and also applying styles and colors .In this post we shall discuss using canvas transformations . When we talk about transformations in Canvas element we have to deal with two main concepts they are

save() restore()

The above mentioned methods are used to save and retrieve the canvas states .The canvas states are stored onto a stack . Every time the save method is called, the current drawing state is pushed onto the stack. A drawing state consists of transformations ,strokestyle ,fillstyle ,linewidth shadowblur values .When the restoration method is called the last saved state is taken from the stack and is exhibited .

A save and restore canvas state example


Here is an example to illustrate the stack process and property exhibition The first step is to draw a large rectangle with the default settings.This state is saved and color is filled .Then we have to draw second blue rectangle and the state should be saved .Again the settings are changed and once again the third semi-rectangle should be saved . No we have to call the restore statement one by one and as we call the restore statement one by one we can notice that the previous saved states are retrieved and their properties are thrown in the fill color section .This might look difficult and a long process for few lines of codes but if the lines of code grow large or else if the code becomes complex to handle this property will be really helpful.

function draw() { var ctx = document.getElementById('canvas').getContext('2d'); ctx.fillRect(0,0,150,150); // Draw a rectangle with default settings ctx.save(); // Save the default state ctx.fillStyle = '#09F' // Make changes to the settings ctx.fillRect(15,15,120,120); // Draw a rectangle with new settings ctx.save(); // Save the current state ctx.fillStyle = '#FFF' // Make changes to the settings ctx.globalAlpha = 0.5; ctx.fillRect(30,30,90,90); // Draw a rectangle with new settings ctx.restore(); // Restore previous state ctx.fillRect(45,45,60,60); // Draw a rectangle with restored settings ctx.restore(); // Restore original state ctx.fillRect(60,60,30,30); // Draw a rectangle with restored settings }

Translating A canvas feature


Translate is one of the canvas transformation methods .This method is used to shift the canvas and its origin point to various points in the matrix . translate(x, y)

This method will take two arguments where the variable x denotes the movement of the element left or right and the y variable denotes the movement of the element up or down. It is a good practice to save the canvas states they can be invoked when there is necessary to be called once again .

Translate Example

This below example shows a demo of the translating example .A function drawspirograph is used to draw spirograph patterns .

If the translate function is not used then only a quarter pattern will be seen .Translate function helps us to place the m anywhere on the canvas and there is no need to move them manually in the spirograph function . In this example the function drawspirograph is called nine times by using two for loops.In both the cases the translation is done in the canvas element and a spirograph is drawn , and finally canvas is returned back to the original state. <pre>function draw() { var ctx = document.getElementById('canvas').getContext('2d'); ctx.fillRect(0,0,300,300); for (var i=0;i<3;i++) { for (var j=0;j<3;j++) { ctx.save(); ctx.strokeStyle = "#9CFF00"; ctx.translate(50+j*100,50+i*100); drawSpirograph(ctx,20*(j+2)/(j+1),-8*(i+3)/(i+1),10); ctx.restore(); } } } function drawSpirograph(ctx,R,r,O){ var x1 = R-O; var y1 = 0; var i = 1; ctx.beginPath(); ctx.moveTo(x1,y1); do { if (i>20000) break; var x2 = (R+r)*Math.cos(i*Math.PI/72) - (r+O)*Math.cos(((R+r)/r)*(i*Math.PI/72)) var y2 = (R+r)*Math.sin(i*Math.PI/72) - (r+O)*Math.sin(((R+r)/r)*(i*Math.PI/72)) ctx.lineTo(x2,y2); x1 = x2; y1 = y2; i++; } while (x2 != R-O && y2 != 0 );

ctx.stroke(); }</pre>

Rotating -Canvas Transformation method


In the previous post we discussed about canvas <a href=http://learnhtml5.info/2011/10/translating-a-canvas-feature/ >translation</a> method and now in this post we will discuss about another transformation method rotate. Using rotate method we can rotate the canvas element around the origin .

Rotate
This method takes angle as the parameter and the canvas element is rotated about this angle .This is shown in the figure below.

The rotation point is the origin of the canvas . Inorder to change the center point ,we have to use the

translate method. A rotate example


In the below example we can use the rotate method to draw shapes around a circular pattern .We can also calculate the individual x and y co-ordinate . When we calculate co-ordinates we can alter the center position of the circle but not the circle themselves We use two loops here the 1st one is used to specify the number of rings and the second one is used to determine the dots that has to be drawn in each pixel. Before drawing each circle the states are saved and the canvas co-ordinates are rotated by an angle that is specified by the total number of dots in the rings .The inner circle has 6 dots and in each and every step the angle is rotated by 360/6=60 degrees .With each new ring the total number of dots in the circle is doubled and the

angle turn is reduced to half

<pre>function draw() { var ctx = document.getElementById('canvas').getContext('2d'); ctx.translate(75,75); for (var i=1;i<6;i++){ // Loop through rings (from inside to out) ctx.save(); ctx.fillStyle = 'rgb('+(51*i)+','+(255-51*i)+',255)'; for (var j=0;j<i*6;j++){ // draw individual dots ctx.rotate(Math.PI*2/(i*6)); ctx.beginPath(); ctx.arc(0,i*12.5,5,0,Math.PI*2,true); ctx.fill(); } ctx.restore(); } }</pre>

Scaling A canvas element


We have discussed many transformations method in the previous posts and in this post we shall discuss about scaling in the canvas element .Scaling can be used to resize the shape using the function scale(x,y). This method takes 2 parameters where the parameter x is used to move in the horizontal direction and y is for the vertical direction . Both the x and y parameters should be a real value only .Values that are smaller than 1 will increase the unit size. If the scaling factor is set to 1 then this wont affect the unit size . We can do axis mirroring using negative numbers .

Scaling example
In the previous example spirograph function is used to draw shapes with various scaling factor . The top left shape does not have any scaling factor with x and y parameters.Here scale method is used twice with the with the same parameters values for the 2nd and 3rd spirograph.

There is a non-uniform scaling applied on the blue shapes in the vertical direction .All these shapes has a scaling factor .If the scaling factor is set to 1.0 then no scaling is applied. The scaling factor of y is set to 0.75 .This makes the original circular shape an ellipse . The green shapes in the 3rd row is similar to the above said steps. <pre>function draw() { var ctx = document.getElementById('canvas').getContext('2d'); ctx.strokeStyle = "#fc0"; ctx.lineWidth = 1.5; ctx.fillRect(0,0,300,300); // Uniform scaling ctx.save() ctx.translate(50,50); drawSpirograph(ctx,22,6,5); // no scaling ctx.translate(100,0); ctx.scale(0.75,0.75); drawSpirograph(ctx,22,6,5); ctx.translate(133.333,0); ctx.scale(0.75,0.75); drawSpirograph(ctx,22,6,5); ctx.restore(); // Non-uniform scaling (y direction) ctx.strokeStyle = "#0cf"; ctx.save() ctx.translate(50,150); ctx.scale(1,0.75); drawSpirograph(ctx,22,6,5); ctx.translate(100,0); ctx.scale(1,0.75); drawSpirograph(ctx,22,6,5); ctx.translate(100,0); ctx.scale(1,0.75); drawSpirograph(ctx,22,6,5);

ctx.restore(); // Non-uniform scaling (x direction) ctx.strokeStyle = "#cf0"; ctx.save() ctx.translate(50,250); ctx.scale(0.75,1); drawSpirograph(ctx,22,6,5); ctx.translate(133.333,0); ctx.scale(0.75,1); drawSpirograph(ctx,22,6,5); ctx.translate(177.777,0); ctx.scale(0.75,1); drawSpirograph(ctx,22,6,5); ctx.restore(); }

Transforms-Canvas transformation element


This transform attribute in canvas transformation element it will allow us to modify the transformation matrix. transform(m11, m12, m21, m22, dx, dy) transform method can be used to multiply the present transformation matrix with the matrix described by m11 m21 dx m12 m22 dy 001 The transformation matrix must be marked infinity if any of the arguments are set infinite instead of throwing an exception . setTransform(m11, m12, m21, m22, dx, dy) This method can be used to reset the current transform to an identity (1 0 0) matrix and then once transformed invoke the method with the same arguments .If any arguments are set infinite the transformation matrix should also be marked infinite instead of handling an exception .

Transform Example
<pre>function draw() { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var sin = Math.sin(Math.PI/6); var cos = Math.cos(Math.PI/6); ctx.translate(200, 200); var c = 0; for (var i=0; i <= 12; i++) { c = Math.floor(255 / 12 * i); ctx.fillStyle = "rgb(" + c + "," + c + "," + c + ")"; ctx.fillRect(0, 0, 100, 10); ctx.transform(cos, sin, -sin, cos, 0, 0); } ctx.setTransform(-1, 0, 0, 1, 200, 200); ctx.fillStyle = "rgba(255, 128, 255, 0.5)"; ctx.fillRect(0, 50, 100, 100); }

Clipping paths
Clipping an area is just like normal canvas shape it helps in masking the unnecessary parts of the shapes . The image towards the right showcases a masked image . The star which is red in color will be used to clip through the surface .what ever the area that falls outside this clipping area will not be displayed.

In this post we will discuss about the clipping paths using the canvas clip() method.

clip()
This canvas elements clip() method can be used to create new clipping path .By default this canvas element has a clipping path that has the same size as that of the canvas .

A clip example
In the below example a circular clip is used to reduce the area of the stars that is spread over the picture .

Initially a black rectangle in the background is drawn using the canvas draw() element using the origin to the center . Below this a circular clipping path is drawn using an arc .If we wanted to keep the original clipping path we should save the canvas state before we create a new one. function draw() { var ctx = document.getElementById('canvas').getContext('2d'); ctx.fillRect(0,0,150,150); ctx.translate(75,75); // Create a circular clipping path ctx.beginPath(); ctx.arc(0,0,60,0,Math.PI*2,true); ctx.clip(); // draw background var lingrad = ctx.createLinearGradient(0,-75,0,75); lingrad.addColorStop(0, '#232256'); lingrad.addColorStop(1, '#143778'); ctx.fillStyle = lingrad; ctx.fillRect(-75,-75,150,150); // draw stars for (var j=1;j<50;j++){ ctx.save(); ctx.fillStyle = '#fff'; ctx.translate(75-Math.floor(Math.random()*150),

75-Math.floor(Math.random()*150)); drawStar(ctx,Math.floor(Math.random()*4)+2); ctx.restore(); } } function drawStar(ctx,r){ ctx.save(); ctx.beginPath() ctx.moveTo(r,0); for (var i=0;i<9;i++){ ctx.rotate(Math.PI/5); if(i%2 == 0) { ctx.lineTo((r/0.525731)*0.200811,0); } else { ctx.lineTo(r,0); } } ctx.closePath(); ctx.fill(); ctx.restore(); }

Você também pode gostar