HTML5 Introduction

Example <!DOCTYPE HTML> <html> <body> <video width="320" height="240" controls> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> Your browser does not support the video tag. </video> </body> </html>

What is HTML5?
HTML5 is the latest standard for HTML. The previous version of HTML, HTML 4.01, came in 1999, and the internet has changed significantly since then. HTML5 was designed to replace both HTML 4, XHTML, and the HTML DOM Level 2. It was specially designed to deliver rich content without the need for additional plugins. The current version delivers everything from animation to graphics, music to movies, and can also be used to build complicated web applications. HTML5 is also cross-platform. It is designed to work whether you are using a PC, or a Tablet, a Smartphone, or a Smart TV.

How Did HTML5 Get Started?
HTML5 is a cooperation between the World Wide Web Consortium (W3C) and the Web Hypertext Application Technology Working Group (WHATWG). WHATWG was working with web forms and applications, and W3C was working with XHTML 2.0. In 2006, they decided to cooperate and create a new version of HTML. Some rules for HTML5 were established:   New features should be based on HTML, CSS, DOM, and JavaScript The need for external plugins (like Flash) should be reduced

   

Error handling should be easier than in previous versions Scripting has to be replaced by more markup HTML5 should be device-independent The development process should be visible to the public

The HTML5 <!DOCTYPE>
In HTML5 there is only one <!doctype> declaration, and it is very simple:

<!DOCTYPE html>

A Minimum HTML5 Document
Below is a simple HTML5 document, with the minimum of required tags:

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title of the document</title> </head> <body> Content of the document...... </body> </html>

HTML5 - New Features
Some of the most interesting new features in HTML5 are:      The <canvas> element for 2D drawing The <video> and <audio> elements for media playback Support for local storage New content-specific elements, like <article>, <footer>, <header>, <nav>, <section> New form controls, like calendar, date, time, email, url, search

Browser Support for HTML5

All major browsers (Chrome, Firefox, Internet Explorer, Safari, Opera) support the new HTML5 elements and APIs, and continue to add new HTML5 features to their latest versions. The HTML 5 working group includes AOL, Apple, Google, IBM, Microsoft, Mozilla, Nokia, Opera, and hundreds of other vendors.

HTML5 New Elements
New Elements in HTML5
The internet, and the use of the internet, has changed a lot since 1999, when HTML 4.01 became a standard. Today, several elements in HTML 4.01 are obsolete, never used, or not used the way they were intended. All those elements are removed or re-written in HTML5. To better handle today's internet needs, HTML5 has also included new elements for drawing graphics, displaying media content, for better page structure and better form handling, and several new APIs for drag and drop, for finding your geological location, for storing local data, and more. Below is a list of the new HTML elements, introduced by HTML5, and a description of what they are used for.

The New <canvas> Element
Note: The links in the tables below point to our HTML5 Reference. However, you will learn more about these new elements in this tutorial. Tag <canvas> Description Defines graphic drawing using JavaScript

New Media Elements
Tag <audio> <video> Description Defines sound or music content Defines video or movie content

<source> <track> <embed>

Defines sources for <video> and <audio> Defines tracks for <video> and <audio> Defines containers for external applications (like plug-ins)

New Form Elements
Tag <datalist> <keygen> <output> Description Defines pre-defined options for input controls Defines a key-pair generator field (for forms) Defines the result of a calculation

New Semantic/Structural Elements
HTML5 offers new elements for better structure: Tag <header> <hgroup> <nav> <section> <main> <article> <aside> <footer> <details> <summary> <figure> <figcaption> Description Defines a header for the document or a section Groups heading elements Defines navigation links in the document Defines a section in the document Defines the main content of a document Defines an article in the document Defines content aside from the page content Defines a footer for the document or a section Defines additional details that the user can view or hide Defines a visible heading for a <details> element Defines self-contained content, like illustrations, diagrams, photos, code listings, etc. Defines a caption for a <figure> element

<mark> <time> <bdi> <wbr> <dialog> <command> <meter> <progress> <ruby> <rt> <rp> Defines marked or highlighted text Defines a date/time Defines a part of text that might be formatted in a different direction from other text outs Defines a possible line-break Defines a dialog box or window Defines a command button that a user can invoke Defines a scalar measurement within a known range (a gauge) Defines the progress of a task Defines a ruby annotation (for East Asian typography) Defines an explanation/pronunciation of characters (for East Asian typography) Defines what to show in browsers that do not support ruby annotations Removed Elements The following HTML 4. . Semantic elements = Elements with meaning.01 elements has been removed from HTML5:             <acronym> <applet> <basefont> <big> <center> <dir> <font> <frame> <frameset> <noframes> <strike> <tt> HTML5 Semantic Elements Semantic = Meaning.

Look at the end of this chapter. Safari and Opera supports the semantic elements described in this chapter. However. New Semantic Elements in HTML5 Many of existing web sites today contains HTML code like this: <div id="nav">. Firefox. Browser Support Internet Explorer 9+. Examples of semantic elements: <form>. header.Clearly defines its content. <div class="header">. and <img> . Note: Internet Explorer 8 and earlier does not support these elements. Examples of non-semantic elements: <div> and <span> .Tells nothing about its content. to indicate navigation links. Chrome.What are Semantic Elements? A semantic element clearly describes its meaning to both the browser and the developer. and footer. or <div id="footer">. there is a solution. <table>. HTML5 offers new semantic elements to clearly define different parts of a web page:             <header> <nav> <section> <article> <aside> <figure> <figcaption> <footer> <details> <summary> <mark> <time> .

</p> </section> HTML5 <article> Element The <article> element specifies independent." Example <section> <h1>WWF</h1> <p>The World Wide Fund for Nature (WWF) is. Examples of where an <article> element can be used:     Forum post Blog post News story Comment Example . According to W3C's HTML5 documentation: "A section is a thematic grouping of content. self-contained content..HTML5 <section> Element The <section> element defines a section in a document.. An article should make sense on its own and it should be possible to distribute it independently from the rest of the web site.. typically with a heading.

The <nav> element is intended for large blocks of navigation links. .</p> </article> HTML5 <nav> Element The <nav> element defines a set of navigation links.</p> <aside> <h4>Epcot Center</h4> <p>The Epcot Center is a theme park in Disney World.. 2011 at 21:00 PDT. not all links in a document should be inside a <nav> element! Example <nav> <a href="/html/">HTML</a> | <a href="/css/">CSS</a> | <a href="/js/">JavaScript</a> | <a href="/jquery/">jQuery</a> </nav> Try it yourself » HTML5 <aside> Element The <aside> element defines some content aside from the content it is placed in (like a sidebar).</p> </aside> Try it yourself » HTML5 <header> Element The <header> element specifies a header for a document or section. However. The aside content should be related to the surrounding content..<article> <h1>Internet Explorer 9</h1> <p>Windows Internet Explorer 9 (abbreviated as IE9) was released to the public on March 14. Florida. Example <p>My family and I visited The Epcot center this summer...

photos. 2011 at 21:00 PDT.The <header> element should be used as a container for introductory content. You can have several <footer> elements in one document. .. A footer typically contains the author of the document. links to terms of use. like illustrations. its position is independent of the main flow. diagrams.. While the content of the <figure> element is related to the main flow. and if removed it should not affect the flow of the document. code listings. contact information.</p> </article> Try it yourself » HTML5 <footer> Element The <footer> element specifies a footer for a document or section. Example <footer> <p>Posted by: Hege Refsnes</p> <p><time pubdate datetime="2012-03-01"></time></p> </footer> Try it yourself » HTML5 <figure> and <figcaption> Elements The <figure> tag specifies self-contained content. The following example defines a header for an article: Example <article> <header> <h1>Internet Explorer 9</h1> <p><time pubdate datetime="2011-03-15"></time></p> </header> <p>Windows Internet Explorer 9 (abbreviated as IE9) was released to the public on March 14. You can have several <header> elements in one document. A <footer> element should contain information about its containing element.. copyright information. etc.. etc.

footer.com/p/html5shiv/ To enable the HTML5 Shiv (after downloading). <nav>. You can download and read more about the HTML5 Shiv at: http://code.The <figcaption> tag defines a caption for a <figure> element. The <figcaption> element can be placed as the first or last child of the <figure> element. . article. aside. section.google. Thankfully. to enable styling of HTML5 elements in versions of Internet Explorer prior to version 9. insert the following code into the <head> element: <!--[if lt IE 9]> <script src="html5shiv. <section>.</figcaption> </figure> Try it yourself » Can We Start Using These Semantic Elements? The elements explained above are all block elements (except <figcaption>). <footer>.The Pulpit Pock. <article>.jpg" alt="The Pulpit Rock" width="304" height="228"> <figcaption>Fig1. main. Example <figure> <img src="img_pulpit. } Problem With Internet Explorer 8 And Earlier IE8 and earlier does not know how to render CSS on elements that it doesn't recognize. set the display property to block in your style sheet (this causes older browsers to render these elements correctly): header. nav. Sjoerd Visscher has discovered a JavaScript workaround called HTML5 Shiv. You cannot style new HTML5 elements like <header>. <figure>. figure { display: block. Norway. To get these elements to work properly in older browsers. <aside>.js"></script> <![endif]--> .

photos. It must be placed in the <head> element because Internet Explorer needs to know about the elements before it renders them. Tag <article> <aside> <details> <figcaption> <figure> <footer> <header> <hgroup> <main> <mark> <nav> <section> <summary> <time> Description Defines an article Defines content aside from the page content Defines additional details that the user can view or hide Defines a caption for a <figure> element Specifies self-contained content. like illustrations. diagrams.The code above is a comment that only versions earlier than IE9 reads. code listings. Semantic Elements in HTML5 Below is an alphabetical list of the new semantic elements in HTML5. The links goes to our complete HTML5 Reference. e Defines a footer for a document or section Specifies a header for a document or section Groups heading elements Specifies the main content of a document Defines marked/highlighted text Defines navigation links Defines a section in a document Defines a visible heading for a <details> element Defines a date/time .

However. you can already start using them. they will behave as regular text fields. These new features allow better input control and validation. Example Select a color from a color picker: Select your favorite color: <input type="color" name="favcolor"> Try it yourself » . Input Type: color The color type is used for input fields that should contain a color. If they supported. This chapter covers the new input types:              color date datetime datetime-local email month number range search tel time url week Not all browsers support all the new input types.HTML5 Input Type HTML5 New Input Types HTML5 has several new input types for forms.

Example Define a date control: Birthday: <input type="date" name="bday"> Try it yourself » Input Type: datetime The datetime type allows the user to select a date and time (with time zone). Example Define a date and time control (with time zone): Birthday (date and time): <input type="datetime" name="bdaytime"> Try it yourself » Input Type: datetime-local The datetime-local type allows the user to select a date and time (no time zone). Example Define a date and time control (no time zone): Birthday (date and time): <input type="datetime-local" name="bdaytime"> Try it yourself » Input Type: email .Input Type: date The date type allows the user to select a date.

The email type is used for input fields that should contain an e-mail address. and changes the on-screen keyboard to match it (adds @ and .com options). You can also set restrictions on what numbers are accepted: Example Define a numeric field (with restrictions): Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5"> Try it yourself » Use the following attributes to specify restrictions: . Example Define a field for an e-mail address (will be automatically validated when submitted): E-mail: <input type="email" name="email"> Try it yourself » Tip: Safari on iPhone recognizes the email type. Example Define a month and year control (no time zone): Birthday (month and year): <input type="month" name="bdaymonth"> Try it yourself » Input Type: number The number type is used for input fields that should contain a numeric value. Input Type: month The month type allows the user to select a month and year.

or Google search): Search Google: <input type="search" name="googlesearch"> Try it yourself » .specifies the legal number intervals value . Example Define a search field (like a site search. Example Define a control for entering a number whose exact value is not important (like a slider control): <input type="range" name="points" min="1" max="10"> Try it yourself » Use the following attributes to specify restrictions:     max .specifies the legal number intervals value . You can also set restrictions on what numbers are accepted.specifies the minimum value allowed step .specifies the minimum value allowed step .Specifies the default value Input Type: search The search type is used for search fields (a search field behaves like a regular text field).Specifies the default value Try an example with all the restriction attributes: Try it yourself Input Type: range The range type is used for input fields that should contain a value from a range of numbers.    max .specifies the maximum value allowed min .specifies the maximum value allowed min .

and changes the on-screen keyboard to match it (adds .com option). Example Define a control for entering a time (no time zone): Select a time: <input type="time" name="usr_time"> Try it yourself » Input Type: url The url type is used for input fields that should contain a URL address. Example Define a field for entering a URL: Add your homepage: <input type="url" name="homepage"> Try it yourself » Tip: Safari on iPhone recognizes the url input type. The value of the url field is automatically validated when the form is submitted. Example Define a field for entering a telephone number: Telephone: <input type="tel" name="usrtel"> Try it yourself » Input Type: time The time type allows the user to select a time. .Input Type: tel The tel type is used for input fields that should contain a telephone number.

Input Type: week The week type allows the user to select a week and year. HTML5 <datalist> Element The <datalist> element specifies a list of pre-defined options for an <input> element. they will behave as regular text fields. However. you can already start using them. If th supported. Example Define a week and year control (no time zone): Select a week: <input type="week" name="week_year"> Try it yourself » HTML5 <input> Tag Tag <input> Description Defines an input control HTML5 Form Elements « Previous Next Chapter » HTML5 New Form Elements HTML5 has the following new form elements:    <datalist> <keygen> <output> Not all browsers support all the new form elements. .

Example A form with a keygen field: <form action="demo_keygen.asp" method="get"> Username: <input type="text" name="usr_name"> Encryption: <keygen name="security"> <input type="submit"> </form> Try it yourself » . two keys are generated. Example An <input> element with pre-defined values in a <datalist>: <input list="browsers"> <datalist id="browsers"> <option value="Internet Explorer"> <option value="Firefox"> <option value="Chrome"> <option value="Opera"> <option value="Safari"> </datalist> Try it yourself » HTML5 <keygen> Element The purpose of the <keygen> element is to provide a secure way to authenticate users. The <keygen> tag specifies a key-pair generator field in a form. and the public key is sent to the server. Users will see a drop-down list of pre-defined options as they input data. Use the <input> element's list attribute to bind it together with a <datalist> element. When the form is submitted. The private key is stored locally. one private and one public. The public key could be used to generate a client certificate to authenticate the user in the future.The <datalist> element is used to provide an "autocomplete" feature on <input> elements.

value)+parseInt(b.HTML5 <output> Element The <output> element represents the result of a calculation (like one performed by a script). New attributes for <form>:   autocomplete novalidate New attributes for <input>:   autocomplete autofocus .value=parseInt(a.value)">0 <input type="range" id="a" value="50">100 + <input type="number" id="b" value="50">= <output name="x" for="a b"></output> </form> Try it yourself » HTML5 New Form Elements Tag <datalist> <keygen> <output> Description Specifies a list of pre-defined options for an <input> element Specifies a key-pair generator field in a form Represents the result of a calculation HTML5 Form Attributes « Previous Next Chapter » HTML5 New Form Attributes HTML5 has several new attributes for <form> and <input>. Example Perform a calculation and show the result in an <output> element: <form oninput="x.

When autocomplete is on. or vice versa.              form formaction formenctype formmethod formnovalidate formtarget height and width list min and max multiple pattern (regexp) placeholder required step <form> / <input> autocomplete Attribute The autocomplete attribute specifies whether a form or input field should have autocomplete on or off. search. password. Tip: It is possible to have autocomplete "on" for the form. Example An HTML form with autocomplete on (and off for one input field): <form action="demo_form. the browser automatically complete values based on values that the user has entered before. datepickers. and color. range.asp" autocomplete="on"> First name:<input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br> E-mail: <input type="email" name="email" autocomplete="off"><br> <input type="submit"> </form> Try it yourself » Tip: In some browsers you may need to activate the autocomplete function for this to work. email. . Note: The autocomplete attribute works with <form> and the following <input> types: text. url. tel. and "off" for specific input fields.

When present. it specifies that the form-data (input) should not be validated when submitted. it specifies that an <input> element should automatically get focus when the page loads. Example Indicates that the form is not to be validated on submit: <form action="demo_form. Tip: To refer to more than one form. Example . use a space-separated list of form ids.<form> novalidate Attribute The novalidate attribute is a boolean attribute. Example Let the "First name" input field automatically get focus when the page loads: First name:<input type="text" name="fname" autofocus> Try it yourself » <input> form Attribute The form attribute specifies one or more forms an <input> element belongs to. When present.asp" novalidate> E-mail: <input type="email" name="user_email"> <input type="submit"> </form> Try it yourself » <input> autofocus Attribute The autofocus attribute is a boolean attribute.

The formaction attribute overrides the action attribute of the <form> element. with different actions: <form action="demo_form. Example . Note: The formenctype attribute is used with type="submit" and type="image". Example An HTML form with two submit buttons.asp" value="Submit as admin"> </form> Try it yourself » <input> formenctype Attribute The formenctype attribute specifies how the form-data should be encoded when submitting it to the server (only for forms with method="post") The formenctype attribute overrides the enctype attribute of the <form> element.asp"> First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br> <input type="submit" value="Submit"><br> <input type="submit" formaction="demo_admin. Note: The formaction attribute is used with type="submit" and type="image".asp" id="form1"> First name: <input type="text" name="fname"><br> <input type="submit" value="Submit"> </form> Last name: <input type="text" name="lname" form="form1"> Try it yourself » <input> formaction Attribute The formaction attribute specifies the URL of a file that will process the input control when the form is submitted.An input field located outside the HTML form (but still a part of the form): <form action="demo_form.

Note: The formnovalidate attribute can be used with type="submit".asp" method="get"> First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br> <input type="submit" value="Submit"> <input type="submit" formmethod="post" formaction="demo_post. it specifies that the <input> element should not be validated when submitted. The formnovalidate attribute overrides the novalidate attribute of the <form> element. Note: The formmethod attribute can be used with type="submit" and type="image". Example The second submit button overrides the HTTP method of the form: <form action="demo_form. . and encoded as "multipart/form-data" (the second submit button): <form action="demo_post_enctype.Send form-data that is default encoded (the first submit button). When present.asp" method="post"> First name: <input type="text" name="fname"><br> <input type="submit" value="Submit"> <input type="submit" formenctype="multipart/form-data" value="Submit as Multipart/form-data"> </form> Try it yourself » <input> formmethod Attribute The formmethod attribute defines the HTTP method for sending form-data to the action URL.asp" value="Submit using POST"> </form> Try it yourself » <input> formnovalidate Attribute The novalidate attribute is a boolean attribute. The formmethod attribute overrides the method attribute of the <form> element.

Tip: Always specify both the height and width attributes for images. and cannot . Note: The height and width attributes are only used with <input type="image">. the space required for the image is reserved when the page is loaded.asp"> E-mail: <input type="email" name="userid"><br> <input type="submit" value="Submit"><br> <input type="submit" formnovalidate value="Submit without validation"> </form> Try it yourself » <input> formtarget Attribute The formtarget attribute specifies a name or a keyword that indicates where to display the response that is received after submitting the form. Example A form with two submit buttons.Example A form with two submit buttons (with and without validation): <form action="demo_form. with different target windows: <form action="demo_form. the browser does not know the size of the image. If height and width are set. Note: The formtarget attribute can be used with type="submit" and type="image".asp"> First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br> <input type="submit" value="Submit as normal"> <input type="submit" formtarget="_blank" value="Submit to a new window"> </form> Try it yourself » <input> height and width Attributes The height and width attributes specify the height and width of an <input> element. without these attributes. However. The formtarget attribute overrides the target attribute of the <form> element.

datetime-local. Note: The min and max attributes works with the following input types: number. with height and width attributes: <input type="image" src="img_submit. date. The effect will be that the page layout will change during loading (while the images load).reserve the appropriate space to it.gif" alt="Submit" width="48" height="48"> Try it yourself » <input> list Attribute The list attribute refers to a <datalist> element that contains pre-defined options for an <input> element. Example An <input> element with pre-defined values in a <datalist>: <input list="browsers"> <datalist id="browsers"> <option value="Internet Explorer"> <option value="Firefox"> <option value="Chrome"> <option value="Opera"> <option value="Safari"> </datalist> Try it yourself » <input> min and max Attributes The min and max attributes specify the minimum and maximum value for an <input> element. datetime. month. time and week. Example . range. Example Define an image as the submit button.

<input> elements with min and max values: Enter a date before 1980-01-01: <input type="date" name="bday" max="1979-12-31"> Enter a date after 2000-01-01: <input type="date" name="bday" min="2000-01-02"> Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5"> Try it yourself » <input> multiple Attribute The multiple attribute is a boolean attribute. tel. Example . Example A file upload field that accepts multiple values: Select images: <input type="file" name="img" multiple> Try it yourself » <input> pattern Attribute The pattern attribute specifies a regular expression that the <input> element's value is checked against. url. and password. Note: The pattern attribute works with the following input types: text. and file. When present. Tip: Learn more about regular expressions in our JavaScript tutorial. email. Tip: Use the global title attribute to describe the pattern to help the user. it specifies that the user is allowed to enter more than one value in the <input> element. Note: The multiple attribute works with the following input types: email. search.

The short hint is displayed in the input field before the user enters a value. When present. and password. and file. it specifies that an input field must be filled out before submitting the form. email. a sample value or a short description of the expected format). Example An input field with a placeholder text: <input type="text" name="fname" placeholder="First name"> Try it yourself » <input> required Attribute The required attribute is a boolean attribute. email. url.An input field that can contain only three letters (no numbers or special characters): Country code: <input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code"> Try it yourself » <input> placeholder Attribute The placeholder attribute specifies a short hint that describes the expected value of an input field (e.g. search. search. url. tel. number. checkbox. Example A required input field: Username: <input type="text" name="usrname" required> Try it yourself » . date pickers. password. Note: The required attribute works with the following input types: text. radio. tel. Note: The placeholder attribute works with the following input types: text.

a multicolor rectangle. datetime. time and week. 6. Example: if step="3". . etc.<input> step Attribute The step attribute specifies the legal number intervals for an <input> element. Example An input field with a specified legal number intervals: <input type="number" name="points" step="3"> Try it yourself » HTML5 <input> Tag Tag <form> <input> Description Defines an HTML form for user input Defines an input control « Previous Next Chapter » HTML5 Canvas « Previous Next Chapter » The <canvas> element is used to draw graphics. range. on the fly. month. a gradient rectangle. Tip: The step attribute can be used together with the max and min attributes to create a range of legal values. 0. date. on a web page. Note: The step attribute works with the following input types: number. and some multicolor text that is drawn onto the canvas. 3. The example at the left shows a red rectangle. datetime-local. legal numbers could be -3.

You must use a script to actually draw the graphics. Chrome. via scripting (usually JavaScript). and a width and height attribute to define the size of the canvas. use the style attribute: Example <canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000. The markup looks like this: <canvas id="myCanvas" width="200" height="100"></canvas> Note: Always specify an id attribute (to be referred to in a script). Firefox."> </canvas> . text. do not support the <canvas> element. Create a Canvas A canvas is a rectangular area on an HTML page. circles. Canvas has several methods for drawing paths. Note: Internet Explorer 8 and earlier versions. The <canvas> element is only a container for graphics. Tip: You can have multiple <canvas> elements on one HTML page. To add a border. and adding images. the <canvas> element has no border and no content.What is Canvas? The HTML5 <canvas> element is used to draw graphics. boxes. on the fly. and Safari support the <canvas> element. Browser Support Internet Explorer 9+. Opera. Note: By default. and it is specified with the <canvas> element.

Then.getElementById("myCanvas").getContext("2d"). ctx. find the <canvas> element: var c = document. </script> Try it yourself » Example explained: First. boxes. images.width.Try it yourself » Draw Onto The Canvas With JavaScript All drawing on the canvas must be done inside a JavaScript: Example <script> var c = document.0. text. and more. ctx.75).150. var ctx = c.getElementById("myCanvas"). or a pattern. The next two lines draw a red rectangle: ctx.fillRect(0. call its getContext() method (you must pass the string "2d" to the getContext() method): var ctx = c. ctx. Canvas Coordinates The canvas is a two-dimensional grid.getContext("2d"). The getContext("2d") object is a built-in HTML5 object. The fillRect(x.fillRect(0.0.height) method draws a rectangle filled with the current fill style. circles.y. The fillStyle property can be a CSS color.fillStyle = "#FF0000".150. with many properties and methods for drawing paths. .75). The default fillStyle is #000000 (black). a gradient.fillStyle = "#FF0000".

start.y) defines the starting point of the line lineTo(x. we will use the following method:  arc(x.getContext("2d"). Then use the stroke() method to actually draw the line: JavaScript: var c = document. we will use the following two methods:   moveTo(x.stroke(). Example Create a circle with the arc() method: JavaScript: . like stroke(). we must use one of the "ink" methods.75). Try it yourself » To draw a circle on a canvas. var ctx = c.0).r. ctx. the fillRect() method above had the parameters (0. like stroke() or fill().stop) To actually draw the circle.0) So.0.100).getElementById("myCanvas").y.The upper-left corner of the canvas has coordinate (0.0) and draw a 150x75 pixels rectangle. Example Define a starting point in position (0. we must use one of the "ink" methods. ctx.moveTo(0.Paths To draw straight lines on a canvas. ctx.150. and an ending point in position (200.100).lineTo(200.0). Coordinates Example Mouse over the rectangle below to see its x and y coordinates: X Y Canvas . This means: Start at the upper-left corner (0.y) defines the ending point of the line To actually draw the line.

font = "30px Arial".strokeText("Hello World". ctx. ctx. ctx. var ctx = c.10.Draws text on the canvas (no fill) Using fillText(): Example Write a 30px high filled text on the canvas.Text To draw text on a canvas.stroke().beginPath().50).defines the font properties for text fillText(text. Try it yourself » Canvas . the most important property and methods are:    font .getContext("2d").getContext("2d").font = "30px Arial". var ctx = c. Try it yourself » .PI).var c = document. using the font "Arial": JavaScript: var c = document.50).0.x.10. using the font "Arial": JavaScript: var c = document.fillText("Hello World".getElementById("myCanvas").arc(95. var ctx = c. Try it yourself » Using strokeText(): Example Write a 30px high text (no fill) on the canvas.y) . ctx. ctx.2*Math. ctx.Draws "filled" text on the canvas strokeText(text. ctx.getElementById("myCanvas").40.y) .getElementById("myCanvas").x.50.getContext("2d").

like a rectangle.10.r. Shapes on the canvas are not limited to solid colors.150. Using createLinearGradient(): Example Create a linear gradient. var ctx = c. Gradient positions can be anywhere between 0 to 1.x1. // Fill with gradient ctx.y1.80).Canvas ."red"). Try it yourself » Using createRadialGradient(): Example Create a radial/circular gradient.addColorStop(1.r1) . and then draw the shape.fillRect(10.getElementById("myCanvas"). grd. or a line. The addColorStop() method specifies the color stops. circles. Fill rectangle with the gradient: JavaScript: . // Create gradient var grd = ctx. ctx.fillStyle = grd.y.Creates a radial/circular gradient Once we have a gradient object. There are two different types of gradients:   createLinearGradient(x.0).y1) ."white").Creates a linear gradient createRadialGradient(x.addColorStop(0.x1. To use the gradient. and its position along the gradient. text. we must add two or more color stops.0.createLinearGradient(0. Fill rectangle with the gradient: JavaScript: var c = document.y. set the fillStyle or strokeStyle property to the gradient. lines.Gradients Gradients can be used to fill rectangles. grd.getContext("2d"). etc.200. text.

var ctx = c. // Fill with gradient ctx. .addColorStop(0. Try it yourself » Canvas .addColorStop(1.Images To draw an image on a canvas.60.150.createRadialGradient(75.80).getContext("2d").var c = document. grd.90.fillRect(10."red"). ctx.5.100). var ctx = c. we will use the following method:  drawImage(image.y) Image to use: Example Draw the image onto the canvas: JavaScript: var c = document."white").x. grd. // Create gradient var grd = ctx.getContext("2d").fillStyle = grd.getElementById("myCanvas").10.getElementById("myCanvas").50.

scripted. ctx.10). on the fly.drawImage(img. and compressed SVG images are scalable . via scripting (usually JavaScript) HTML5 Inline SVG « Previous Next Chapter » HTML5 has support for inline SVG. Try it yourself » HTML Canvas Reference For a complete reference of all the properties and methods that can be used with the Canvas object (with try-it examples on every property and method). SVG What is SVG?       SVG stands for Scalable Vector Graphics SVG is used to define vector-based graphics for the Web SVG defines the graphics in XML format SVG graphics do NOT lose any quality if they are zoomed or resized Every element and every attribute in SVG files can be animated SVG is a W3C recommendation SVG Advantages Advantages of using SVG over other image formats (like JPEG and GIF) are:    SVG images can be created and edited with any text editor SVG images can be searched. go to our Canvas Reference. indexed.var img = document.10.getElementById("scream"). The HTML <canvas> Tag Tag <canvas> Description Used to draw graphics.

Differences Between SVG and Canvas SVG is a language for describing 2D graphics in XML. please read our SVG Tutorial. you can embed SVG elements directly into your HTML page: Example <!DOCTYPE html> <html> <body> <svg width="300" height="200"> <polygon points="100.180" style="fill:lime. Embed SVG Directly Into HTML Pages In HTML5.  SVG images can be printed with high quality at any resolution SVG images are zoomable (and the image can be zoomed without degradation) Browser Support Internet Explorer 9+. You can attach JavaScript event handlers for an element.60 160.stroke:purple. . Chrome.stroke-width:5. Canvas draws 2D graphics.180 190. Firefox. SVG is XML based. on the fly (with a JavaScript).60 10.10 40. which means that every element is available within the SVG DOM. and Safari support inline SVG." /> </svg> </body> </html> Try it yourself » Result: To learn more about SVG.fill-rule:evenodd. Opera.

videos could only be played with a plug-in (like flash). Canvas is rendered pixel by pixel.jpg Well suited for graphic-intensive games SVG      Resolution independent Support for event handlers Best suited for applications with large rendering (Google Maps) Slow rendering if complex (anything that uses th will be slow) Not suited for game applications HTML5 Video « Previous Next Chapter » Many modern websites show videos. the browser can automatically re-render the shape. In canvas. . If attributes of an SVG object are changed. HTML5 provides a standard for showing them. Comparison of Canvas and SVG The table below shows some important differences between Canvas and SVG: Canvas      Resolution dependent No support for event handlers Poor text rendering capabilities You can save the resulting image as . the entire scene needs to be redrawn. different browsers supported different plug-ins. once the graphic is drawn. including any objects that might have been covered by the graphic.In SVG. there was no standard for showing videos/movies on web pages. If its position should be changed. it is forgotten by the browser. Before HTML5. HTML5 defines a new element which specifies a standard way to embed a video or movie on a web page: the <video> element.png or . Check if your browser supports HTML5 video Check Video on the Web Before HTML5. However. each drawn shape is remembered as an object.

</video> Try it yourself » The control attribute adds video controls. do not support the <video> element.mp4" type="video/mp4"> <source src="movie. without these attributes. and Ogg: Browser Internet Explorer MP4 YES WebM NO Ogg NO . You should also insert text content between the <video> and </video> tags for browsers that do not support the <video> element. pause. and Safari support the <video> element. the browser does not know the size of the video. like play. the space required for the video is reserved when the page is loaded. The browser will use the first recognized format. Note: Internet Explorer 8 and earlier versions. Chrome. The <video> element allows multiple <source> elements. Firefox.Browser Support Internet Explorer 9+. Video Formats and Browser Support Currently. However. It is also a good idea to always include width and height attributes. The effect will be that the page layout will change during loading (while the video loads). If height and width are set. and volume. this is all you need: Example <video width="320" height="240" controls> <source src="movie.How It Works To show a video in HTML5. <source> elements can link to different video files. HTML5 Video . WebM. Opera. there are 3 supported video formats for the <video> element: MP4. and cannot reserve the appropriate space to it.ogg" type="video/ogg"> Your browser does not support the video tag.

and events allow you to manipulate <video> and <audio> elements using JavaScript. and Android now supports MP4 YES NO YES YES YES YES Safari Opera    NO YES NO YES MP4 = MPEG 4 files with H264 video codec and AAC audio codec WebM = WebM files with VP8 video codec and Vorbis audio codec Ogg = Ogg files with Theora video codec and Vorbis audio codec MIME Types for Video Formats Format MP4 WebM Ogg MIME-type video/mp4 video/webm video/ogg HTML5 <video> . etc. for example and there are properties (like duration and volume). There are also DOM events that can notify you when the <video> element begins to play. properties. Windows Vista. and events for the <video> and <audio> elements. is ended. pausing. in a simple way. read and set properties. properties. Example 1 Create simple play/pause + resize controls for a video: .DOM Methods and Properties HTML5 has DOM methods. and loading. These methods.Chrome Firefox YES NO Update: Firefox 21 running on Windows 7. The example below illustrate. There are methods for playing. Windows 8. is paused. how to address a <video> element. and call methods.

The example above calls two methods: play() and pause(). there was no standard for playing audio files on a web page. However. such as <video> and <audio Defines text tracks in media players HTML5 Audio « Previous Next Chapter » HTML5 provides a standard for playing audio files. different browsers supported different plug-ins. HTML5 defines a new element which specifies a standard way to embed an audio file on a web page: the <audio> element. HTML5 Video Tags Tag <video> <source> <track> Description Defines a video or movie Defines multiple media resources for media elements. Before HTML5. Try it yourself » For a full reference go to our HTML5 Audio/Video DOM Reference. audio files had to be played with a plug-in (like flash). Browser Support .Play/Pause Big Small Normal Video courtesy of Big Buck Bunny. It also uses two properties: paused and width. Audio on the Web Before HTML5.

Internet Explorer 9+. Windows 8. </audio> Try it yourself » The control attribute adds audio controls. Windows Vista.ogg" type="audio/ogg"> <source src="horse. and Android now supports MP3 YES NO Wav NO YES YES Ogg NO YES YES Safari Opera YES YES NO YES . do not support the <audio> element. and Safari support the <audio> element. like play. The <audio> element allows multiple <source> elements. You should also insert text content between the <audio> and </audio> tags for browsers that do not support the <audio> element. this is all you need: Example <audio controls> <source src="horse. Wav. and Ogg: Browser Internet Explorer Chrome Firefox MP3 YES YES NO Update: Firefox 21 running on Windows 7. there are 3 supported file formats for the <audio> element: MP3. and volume. <source> elements can link to different audio files. HTML5 Audio . pause. Note: Internet Explorer 8 and earlier versions. Firefox. Opera. Audio Formats and Browser Support Currently.How It Works To play an audio file in HTML5. Chrome.mp3" type="audio/mpeg"> Your browser does not support the audio element. The browser will use the first recognized format.

.MIME Types for Audio Formats Format MP3 Ogg Wav MIME-type audio/mpeg audio/ogg audio/wav HTML5 Audio Tags Tag <audio> <source> HTML5 Geolocation HTML5 Drag/Drop HTML5 Web Storage HTML5 App Cache HTML5 Web Workers HTML5 SSE Description Defines sound content Defines multiple media resources for media elements. such as <video> and <audio> HTML Scripts « Previous Next Chapter » JavaScripts make HTML pages more dynamic and interactive.

visit our JavaScript tutorial! The HTML <noscript> Tag The <noscript> tag is used to provide an alternate content for users that have disabled scripts in their browser or have a browser that doesn't support client-side scripting. Common uses for JavaScript are image manipulation. The <noscript> element can contain all the elements that you can find inside the <body> element of a normal HTML page.Examples Insert a script How to insert a script into an HTML document. .write("Hello World!") </script> Try it yourself » Tip: To learn more about JavaScript. The <script> element either contains scripting statements or it points to an external script file through the src attribute. form validation. The script below writes Hello World! to the HTML output: Example <script> document. and dynamic changes of content. Use of the <noscript> tag How to handle browsers that do not support scripting. or have scripting disabled. such as a JavaScript. The HTML <script> Tag The <script> tag is used to define a client-side script.Try it Yourself .

color="#ff0000". Try it yourself » JavaScript can react to events: <button type="button" onclick="myFunction()">Click Me!</button> Try it yourself » JavaScript can manipulate HTML styles: document.The content inside the <noscript> element will only be displayed if scripts are not supported.write("<p>This is a paragraph</p>"). your browser does not support JavaScript!</noscript> Try it yourself » A Taste of JavaScript (From Our JavaScript Tutorial) Here are some examples of what JavaScript can do: JavaScript can write directly into the HTML output stream: document. or are disabled in the user's browser: Example <script> document.write("Hello World!") </script> <noscript>Sorry.style. Try it yourself » HTML Script Tags Tag <script> <noscript> Description Defines a client-side script Defines an alternate content for users that do not support client-side scripts HTML Styles .CSS « Previous Next Chapter » .getElementById("demo").

This is done to simplify the examples. .. Link to an external style sheet How to use the <link> tag to link to an external style sheet.using an external CSS file The preferred way to add CSS to HTML.using the <style> element in the <head> section External .using the style attribute in HTML elements Internal . Look! Styles and colors M a n i p u l a t e T e x t C o l o r s . You can learn everything about CSS in our CSS Tutorial. Styling HTML with CSS CSS was introduced together with HTML 4. Try it yourself Try it Yourself ..Examples Using styles in HTML How to add style information inside the <head> section. is to put CSS syntax in separate CSS files.CSS (Cascading Style Sheets) is used to style HTML elements. B o x e s and more. CSS can be added to HTML in the following ways:    Inline . It also makes it easier for you to edit the code and try it yourself. Link that is not underlined How to make a link that is not underlined. with the style attribute. to provide a better way to style HTML elements. in this HTML tutorial we will introduce you to CSS using the style attribute. However.

and size of the text in an element: Example <!DOCTYPE html> <html> <body> . The style attribute can contain any CSS property.Background Color The background-color property defines the background color for an element: Example <!DOCTYPE html> <html> <body style="background-color:yellow.">This is a paragraph.margin-left:20px. and font-size properties defines the font. color.</p> </body> </html> Try it yourself » The background-color property makes the "old" bgcolor attribute obsolete.">This is a heading</h2> <p style="background-color:green. HTML Style Example ."> <h2 style="background-color:red. visit our CSS tutorial.Font.">This is a paragraph.</p> To learn more about style sheets. Color and Size The font-family.Inline Styles An inline style can be used if a unique style is to be applied to one single occurrence of an element. color. use the style attribute in the relevant tag. Try it yourself: Background color the old way HTML Style Example . To use inline styles. The example below shows how to change the text color and the left margin of a paragraph: <p style="color:blue.

">Center-aligned heading</h1> <p>This is a paragraph. color.</p> </body> </html> Try it yourself » The font-family.color:red. Try it yourself: Centered heading the old way Internal Style Sheet An internal style sheet can be used if one single document has a unique style.Text Alignment The text-align property specifies the horizontal alignment of text in an element: Example <!DOCTYPE html> <html> <body> <h1 style="text-align:center. HTML Style Example . like this: <head> <style> body {background-color:yellow. Internal styles are defined in the <head> section of an HTML page. and font-size properties make the old <font> tag obsolete.<h1 style="font-family:verdana.font-size:20px.">A paragraph.} </style> </head> . by using the <style> tag.">A heading</h1> <p style="font-family:arial.} p {color:blue.</p> </body> </html> Try it yourself » The text-align property makes the old <center> tag obsolete.

<center>. The <link> tag goes inside the <head> section: <head> <link rel="stylesheet" type="text/css" href="mystyle. With an external style sheet.External Style Sheet An external style sheet is ideal when the style is applied to many pages. several tags and attributes were used to style documents. These tags are not supported in newer versions of HTML. and the attributes: color and bgcolor. and <strike>. .css"> </head> HTML Style Tags Tag <style> <link> Description Defines style information for a document Defines the relationship between a document and an external resource Deprecated Tags and Attributes In HTML 4. Avoid using the elements: <font>. Each page must link to the style sheet using the <link> tag. you can change the look of an entire Web site by changing one file.