Академический Документы
Профессиональный Документы
Культура Документы
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).
<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.
<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>
<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>
<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>
<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" />
<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>
<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>
<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 :
<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.
<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>
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.
<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.
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.
<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.
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++){
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 .
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 }
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>
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
<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 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(); }
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(); }