HTML 5 Flashcards
basic html document
<!DOCTYPE html>
Example 01 This is my first document.
XHTML Example
An HTML Document
Example
This is an example HTML document.
Why XHTML document does not need to include the DOCTYPE
because XHTML documents that are delivered correctly using an XML MIME type and are processed as XML by browsers, are always rendered in no quirks mode. However, the DOCTYPE may optionally be included, and should be included if the document uses the compatible subset of markup that is conforming in both HTML and XHTML, and is ever expected to be used in text/html environments.
Metadata elements
appear within the head of a document. Some common examples of metadata elements include: title, meta, link, script and style.
It is considered good practice to specify the primary language of the document on this element using the ____________ tag
<!DOCTYPE html>
... ...
xmlns attribute
In the XHTML syntax, the xmlns attribute needs to be specified on this element to declare that it is in the HTML namespace. You may use either the lang or xml:lang attribute to specify the langauge.
base element (explanation)
specifying a base URL against which relative links will be resolved, and the name of the default target for opening links and form submissions
base element (example)
- Notice that we have only specified a relative address
….
link element (explanation)
The link is for linking to other resources, such as stylesheets, favicons and syndication feeds.
embed style in document
<!--
...css goes here..
-->
embed java script in a document
My First Web Page
” + Date() + “
noscript element (explanation)
used to provide alternative content for users using browsers that do not support scripting or have it disabled.
noscript element (code)
Check out the current time:
World Time Server
element attributes (list)
onbeforeunload onerror onhashchange onload onmessage onoffline ononline onpopstate onresize onstorage onunload
Tag
WWF
The World Wide Fund for Nature (WWF) is….
Tag
The tag defines a section of navigation links.
Not all links of a document must be in a element. The element is intended only for major block of navigation links.
Browsers, such as screen readers for disabled users, can use this element to determine whether to omit the initial rendering of this content.
Tag
tag specifies independent, self-contained content.
An article should make sense on its own and it should be possible to distribute it independently from the rest of the site.
Tag
Epcot Center
The Epcot Center is a theme park in Disney World, Florida.
Tag
The tag specifies a header for a document or section.
The element should be used as a container for introductory content or set of navigational links.
You can have several elements in one document.
Tag
tag defines a footer for a document or section.
A element should contain information about it’s containing element.
A footer typically contains the author of the document, copyright information, links to terms of use, contact information, etc.
You can have several elements in one document.
Tag (explanation)
<!DOCTYPE html>
Written by Jon Doe.
Visit us at: Example.com
Box 564, Disneyland USA
Tag
tag is supported in all major browsers.
Tag
represents the title of a work, such as an article, a book, a poem, a song, a film, or any other creative work.
, , , , , , and element
The , , , , , , and tags are all phrase tags. They are not deprecated, but it is possible to achieve richer effect with CSS.
Tag
tag defines marked text.
Use the tag if you want to highlight parts of your text.
progress element (code)
Only in Firefox, Opera, Chrome
<!DOCTYPE html>
Downloading progress:
Note: The progress element is currently supported in Firefox, Opera, and Chrome.
meter element (code) Chrome, Opera
<!DOCTYPE html>
2 out of 10
60%
code element (expl+code)
represents a fragment of computer code.
<!DOCTYPE html>
Computer code
var element (expl+code)
represents a fragment of computer code.
<!DOCTYPE html>
variable
sample element (expl+code)
represents a fragment of computer code.
<!DOCTYPE html>
variable
HTML5 and Tags
<!DOCTYPE html>
This text contains subscript text.
This text contains superscript text.
HTML5 Tag (expl)
tag specifies a ruby annotation.
Ruby annotations are used for East Asian typography, to show the pronunciation of East Asian characters.
html comment
<!-- Text here-->
HTML5 <!DOCTYPE> Declaration
The <!DOCTYPE> declaration must be the very first thing in your HTML5 document, before the tag.
The <!DOCTYPE> declaration is not an HTML tag; it is an instruction to the web browser about what version of HTML the page is written in.
HTML5 Tag code
<!DOCTYPE html>
The WHO was founded in 1948.
The WHO was founded in 1948.
——————————————
By marking up abbreviations you can give useful information to browsers, spell checkers, translation systems and search-engine indexers.
HTML5 Tag (expl)
The tag defines an area inside an image-map (an image-map is an image with clickable areas).
The element is always nested inside a tag.
HTML5 Tag (code)
<!DOCTYPE html>
Click on the sun or on one of the planets to watch it closer:
HTML5 Tag
Your browser does not support the audio tag.
HTML5 Tag
Click Me!
The autofocus attribute is supported in all major browsers, except Internet Explorer and Opera.
The autofocus attribute is a boolean attribute.
When present, it specifies that a button should automatically get focus when the page loads.
disabled
Specifies that a button should be disabled
The form attribute is supported in all major browsers, except Internet Explorer.
First name:
Last name:
Submit
HTML5 formaction Attribute
First name:
Last name:
Submit
Submit as admin
A form with two submit buttons. The first submit button submits the form data to “demo_form.asp”, and the second submits to “demo_admin.asp”:
Not in Explorer
First name:
Last name:
Submit
Submit to a new window
HTML5 name Attribute
Choose your favorite subject:
HTML
CSS
HTML5 type Attribute
A form with two buttons. One submit button and one reset button:
——————————————
First name:
Last name:
Submit
Reset
button - clickable button
submit - Default submits form-data
reset - button is a reset button (clears form-data)
HTML5 Tag code
<!DOCTYPE html>
Your browser does not support the canvas tag.
HTML5 height & weight Attribute
specifies height and weight of the cavans
————————————-
HTML5 Tag
The tag defines a table caption.
HTML5 Tag
The tag specifies column properties for each column within a element.
<!DOCTYPE html>
ISBN Title
3476896 My first HTML
5869207 My first CSS
First column will bre read second yellow
HTML5 Tag
The tag specifies a group of one or more columns in a table for formatting.
The tag is useful for applying styles to entire columns, instead of repeating the styles for each cell, for each row.
HTML5 Tag
The tag is used to group related elements in a form.
The tag draws a box around the related elements.
Tip: The tag defines a caption for the element.
HTML5 Tag
The tag defines a caption for a element.
The element can be placed as the first or last child of the element.
HTML5 Tag
The tag specifies self-contained content, like illustrations, diagrams, photos, code listings, etc.
While the content of the element is related to the main flow, its position is independent of the main flow, and if removed it should not affect the flow of the document.
HTML5 Tag
The tag is used to create an HTML form for user input.
The element can contain one or more of the following form elements: • • • • • • • • • •
HTML5 Tag
The tag specifies an input field where the user can enter data.
elements are used within a element to declare input controls that allow users to input data.
An input field can vary in many ways, depending on the type attribute.
HTML5 width Attribute
The width attribute specifies the width of the element.
HTML5 value Attribute
The value attribute specifies the value of an element.
The value attribute is used differently for different input types:
•For “button”, “reset”, and “submit” - it defines the text on the button
•For “text”, “password”, “hidden” - it defines the initial (default) value of the input field
•For “checkbox”, “radio”, “image” - it defines the value associated with the input (this is also the value that is sent on submit)
Note: The value attribute is required with and .
Note: The value attribute cannot be used with .
Refresh document every 30 seconds
Define the last revision of your page:
Define a description of your web page:
Define keywords for search engines:
HTML5 Tag
The tag specifies a header for a document or section.
The element should be used as a container for introductory content or set of navigational links.
You can have several elements in one document.
Note: A tag cannot be placed within a , or another element.
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, indexed, scripted, and compressed
•SVG images are scalable
•SVG images can be printed with high quality at any resolution
•SVG images are zoomable (and the image can be zoomed without degradation)
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
Create a Canvas
Create a Canvas
A canvas is specified with the element.
Specify the id, width, and height of the element:
What is Canvas?
element is used to draw graphics, on the fly, via scripting (usually JavaScript).
The element is only a container for graphics, you must use a script to actually draw the graphics.
A canvas is a drawable region defined in HTML code with height and width attributes.
Canvas has several methods for drawing paths, boxes, circles, characters, and adding images.
code to make drag and drop
div1, #div2 {float:left; width:100px; height:35px; margin:10px;padding:10px;border:1px solid #aaaaaa;}
event.preventDefault()
By default, data/elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element.
This is done by calling the event.preventDefault() method for the ondragover event:
event.preventDefault()
Steps to make an element draggable
1) Make an Element Draggable
2) What to Drag - ondragstart and setData()
3) Where to Drop - ondragover
4) Do the Drop - ondrop
Make an Element Draggable key to add to tag
First of all: To make an element draggable, set the draggable attribute to true:
tag to prevent a page from being cached on users browser
opens the new document in a new window.
a new window
is
non breaking space
What is the tag in HTML5 used for?
The tag is not supported in HTML5. Use the tag instead.
Tag code
W3Schools
Tag explanation
tag specifies the base URL/target for all relative URLs in a document.
There can be at maximum one element in a document, and it must be inside the element.
currently supported only in Firefox and Chrome.
bdi stands for Bi-directional Isolation.
The tag isolates a part of text that might be formatted in a different direction from other text outside it.
This element is useful when embedding user-generated content with an unknown directionality.
all major browsers, except Internet Explorer.
The Word Break Opportunity () specifies where in a text it would be ok to add a line-break.
Tag
The tag is supported in all major browsers.
Tag
The element is used to create a drop-down list.
Volvo
Saab
Opel
Audi
currently supported in Opera, Chrome, and Safari.
The autofocus attribute is a boolean attribute.
When present, it specifies that the drop-down list should automatically get focus when the page loads.
disabled Attribute
The disabled attribute is a boolean attribute.
When present, it specifies that the drop-down list should be disabled.
A disabled drop-down list is unusable and un-clickable.
all major browsers, except Internet Explorer.
The form attribute specifies one or more forms the drop-down list belongs to.
multiple Attribute
The multiple attribute is a boolean attribute.
When present, it specifies that multiple options can be selected at once.
name Attribute
The name attribute specifies the name for a drop-down list.
Volvo
Saab
Opel
Audi
size Attribute
Volvo
Saab
Opel
Audi
Tag
The tag is used to group inline-elements in a document.
The tag provides no visual change by itself.
The tag provides a way to add a hook to a part of a text or a part of a document.
Tag
The tag specifies text that is no longer correct, accurate or relevant by stricking it out.
The tag should not be used to define replaced or deleted text, use the tag to define replaced or deleted text.
Tag
tag defines an explanation or pronunciation of characters (for East Asian typography) in a ruby annotation.
Tag
tag defines what to show if a browser does NOT support ruby annotations.
Tag
dir Attribute
ltr
Specifies left-to-right text direction
rtl
only supported by Internet Explorer 9.
The tag defines a command (a radiobutton, a checkbox, or a command button) that the user can invoke.
Save
Tag
tag is used to describe an item in a definition list.
Tag
same as
del> tag defines a text that has been deleted from a document.
Tag
The tag defines a division or a section in an HTML document.
The tag is used to group block-elements and format them with CSS.
Tag
tag defines an item in a definition list.
———————————-
tag is used in conjunction with (defines the definition list) and (describes the item in the list).
Tag
tag defines a container for an external application or interactive content (a plug-in).
height & weight Attribute
The height and weight attribute specifies the height adn weight of the embedded content, in pixels.
src Attribute
src attribute specifies the address of the external file to embed.
type Attribute
The type attribute specifies the MIME type of the embedded content.
Tag
The tag is not supported in HTML5.
The tag was used to define one particular window (frame) within a frameset.
The and tags are not supported in HTML5, because they have a negative effect on the usability of a web page.
Tag
HTML5 Tags <!--> <!DOCTYPE> <a> <abbr> <acronym> <address> <applet> <area> <article> <aside> <audio> <b> <base> <basefont> <bdi> <bdo> <big> <blockquote> <body> <br> <button> <canvas> <caption> <center> <cite> <code> <col> <colgroup> <command> <datalist> <dd> <del> <details> <dfn> <dir> <div> <dl> <dt> <em> <embed> <fieldset> <figcaption> <figure> <font> <footer> <form> <frame> <frameset> <h1> - <h6> <head> <header> <hgroup> <hr> <html> <i> <iframe> <img> <input> <ins> <keygen> <kbd> <label> <legend> <li> <link> <map> <mark> <menu> <meta> <meter> <nav> <noframes> <noscript> <object> <ol> <optgroup> <option> <output> <p> <param> <pre> <progress> <q> <rp> <rt> <ruby> <s> <samp> <script> <section> <select> <small> <source> <span> <strike> <strong> <style> <sub> <summary> <sup> <table> <tbody> <td> <textarea> <tfoot> <th> <thead> <time> <title> <tr> <track> <tt> <u> <ul> <var> <video> <wbr>
HTML5 <hgroup> Tag
Example
Use <hgroup> to group headings:
<hgroup>
<h1>Welcome to my WWF</h1>
<h2>For a living planet</h2>
</hgroup>
<p>The rest of the content...</p>
Browser Support
The <hgroup> tag is supported in all major browsers.
Definition and Usage
The <hgroup> tag is used to group heading elements.
The <hgroup> element is used to group a set of <h1> to <h6> elements, when a heading has multiple levels (subheadings).
Tag
The tag defines a thematic break in an HTML page (e.g. a shift of topic).
The element is used to separate content (or define a change) in an HTML page.
Tag
tag defines a part of text in an alternate voice or mood. The tag is typically displayed in italic type.
Tag
tag specifies an inline frame.
An inline frame is used to embed another document within the current HTML document.
name Attribute
The name attribute specifies a name for the .
height & weight Attribute
src Attribute
The src attribute specifies the address of the document to embed in the inline frame.
Tag
tag specifies video, such as a movie clip or other video streams.
autoplay Attribute
The autoplay attribute is a boolean attribute.
height & weight Attribute
specifies the height and weight of the video
loop Attribute
The loop attribute is a boolean attribute.
When present, it specifies that the video will start over again, every time it is finished.
all major browsers, except Internet Explorer and Safari.
The muted attribute is a boolean attribute.
When present, it specifies that the audio output of the video should be muted.
poster Attribute
The poster attribute specifies an image to be shown while the video is downloading, or until the user hits the play button. If this is not included, the first frame of the video will be used instead.
preload Attribute
The preload attribute specifies if and how the author thinks that the video should be loaded when the page loads.
The preload attribute allows the author to provide a hint to the browser about what he/she thinks will lead to the best user experience. This attribute may be ignored in some instances.
Tag
tag defines a row in an HTML table.
Tag
The tag defines an ordered list.
Use the tag to define list items.
Tag
tag is used to group header content in an HTML table.
The element is used in conjunction with the and elements to specify each part of a table (header, body, footer).
Tag
The tag defines a header cell in an HTML table.
An HTML table has two kinds of cells:
- Header cells - contains header information (created with the element)
- Standard cells - contains data (created with the element)
The text in elements are bold and centered by default.
The text in elements are regular and left-aligned by default.
scope Attribute
The scope attribute specifies whether a header cell is a header for a column, row, or group of columns or rows.
rowspan Attribute
rowspan attribute defines the number of rows a header cell should span.
Tag
tag is supported in all major browsers.
cols Attribute
The cols attribute specifies the visible width of a text area.
Tip: The size of a textarea can also be set by the CSS height and width properties.
disabled Attribute
The disabled attribute is a boolean attribute.
When present, it specifies that the text area should be disabled.
A disabled text area is unusable and the text is not selectable (cannot be copied).
form Attribute
The form attribute specifies one or more forms the text area belongs to.
all major browsers, except Internet Explorer and Safari.
The required attribute is a boolean attribute.
When present, it specifies that a text area is required/must be filled out (in order to submit the form).
readonly Attribute
The readonly attribute is a boolean attribute.
When present, it specifies that a text area should be read-only.
wrap Attribute
The wrap attribute specifies how the text in a text area is to be wrapped when submitted in a form.
Tag
The tag defines a standard cell in an HTML table.
Tag
The tag is used to group the body content in an HTML table.
The element is used in conjunction with the and elements to specify each part of a table (body, header, footer).
Tag
The tag defines an HTML table.
An HTML table consists of the element and one or more , , and elements.
Tag
The tag is used to define style information for an HTML document.
Inside the element you specify how HTML elements should render in a browser.
Each HTML document can contain multiple tags.
Tag
The tag is used to specify multiple media resources for media elements, such as and .
The tag allows you to specify alternative video/audio files which the browser may choose from, based on its media type or codec support.
Tag
Browsers often insert quotation marks around the quotation.
Tag
tag defines preformatted text.
Text in a element is displayed in a fixed-width font (usually Courier), and it preserves both spaces and line breaks.
Tag
The tag is used to define parameters for plugins embedded with an element.
Tip: HTML 5 also includes two new elements for playing audio or video: The and tags.
Tag
The tag defines an option in a select list.
The element goes inside a or element.
Tag
The is used to group related options in a drop-down list.
If you have a long list of options, groups of related options are easier to handle for a user.
Tag
The tag defines an embedded object within an HTML document. Use this element to embed multimedia (like audio, video, Java applets, ActiveX, PDF, and Flash) in your web pages.
You can also use the tag to embed another webpage into your HTML document.
You can use the tag to pass parameters to plugins that have been embedded with the tag.
Tagv
Not Supported in HTML5.
Tag
areas.
The name attribute of the element is associated with the ‘s usemap attribute and creates a relationship between the image and the map.
The element contains a number of elements, that defines the clickable areas in the image map.
Tag
The tag defines the relationship between a document and an external resource.
The tag is most used to link to style sheets.
type Attribute
The type attribute specifies the MIME type of the linked document/resource.
This attribute is only used if the href attribute is set.
A very common MIME type for is “text/css”, which specifies a style sheet.
rel Attribute
The required rel attribute specifies the relationship between the current document and the linked document/resource.
rel Attribute values 1
- alternate - Links to an alternate version of the document (i.e. print page, translated or mirror)
- author - Links to the author of the document
- help - Links to a help document
- icon - Imports an icon to represent the document
- license - Links to copyright information for the document
rel Attribute values 2
- next - Indicates that the document is a part of a series, and that the next document in the series is the referenced document
- prefetch - Specifies that the target resource should be cached
- prev - Indicates that the document is a part of a series, and that the previous document in the series is the referenced document
- search - Links to a search tool for the document
- stylesheet - URL to a style sheet to import
Tag
The tag defines a list item.
The tag is used in ordered lists(), unordered lists (), and in menu lists ().
Tag
The tag defines a caption for the , , and the elements
Tag
tag defines a label for an element.
The element does not render as anything special for the user. However, it provides a usability improvement for mouse users, because if the user clicks on the text within the element, it toggles the control.
Tag
tag specifies a key-pair generator field used for forms.
When the form is submitted, the private key is stored locally, and the public key is sent to the server.
Tag
tag defines a text that has been inserted into a document.
Tag
The tag defines an image in an HTML page.
The tag has two required attributes: src and alt.
Note: Images are not technically inserted into an HTML page, images are linked to HTML pages. The tag creates a holding space for the referenced image.
Tip: To link an image to another document, simply nest the tag inside tags.
Make an Element Draggable
What to Drag - ondragstart
ondragstart attribute calls a function, drag(event), that specifies what data to be dragged.
method sets the data type and the value of the dragged data
function drag(ev) { ev.dataTransfer.setData("Text",ev.target.id); }
Where to Drop - ondragover
The ondragover event specifies where the dragged data can be dropped.
By default, data/elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element.
This is done by calling the event.preventDefault() method for the ondragover event:
event.preventDefault()
Do the Drop - ondrop
When the dragged data is dropped, a drop event occurs.
In the example above, the ondrop attribute calls a function, drop(event):
function drop(ev) { var data=ev.dataTransfer.getData("Text"); ev.target.appendChild(document.getElementById(data)); ev.preventDefault(); }
draww lines in canvas code
<!DOCTYPE html>
Your browser does not support the canvas element.
HTML5 Geolocation
HTML5 Geolocation API is used to get the geographical position of a user.
Since this can compromise user privacy, the position is not available unless the user approves it.
method to get the user’s position
getCurrentPosition()
Geolocation error codes
- Permission denied - The user did not allow Geolocation
- Position unavailable - It is not possible to get the current location
- Timeout - The operation timed out
simple Geolocation example returning the latitude and longitude of the user’s position code
<!DOCTYPE html>
Click the button to get your coordinates:
Try It Longitude: “ + position.coords.longitude; }
display the result in a map, you need access to a map service that can use latitude and longitude, like Google Maps
<!DOCTYPE html>
Click the button to get your position:
Try It
“; }
getCurrentPosition() Method - Return Data
coords.latitude - The latitude as a decimal number
coords.longitude - The longitude as a decimal number
coords.accuracy - The accuracy of position
coords.altitude - The altitude in meters above the mean sea level
coords.altitudeAccuracy - he altitude accuracy of position
coords.heading - The heading as degrees clockwise from North
coords.speed - The speed in meters per second
timestamp - The date/time of the response
watchPosition()
Returns the current position of the user and continues to return updated position as the user moves (like the GPS in a car).
clearWatch()
Stops the watchPosition() method.
What is HTML5 Web Storage?
With HTML5, web pages can store data locally within the user’s browser.
Earlier, this was done with cookies. However, Web Storage is more secure and faster. The data is not included with every server request, but used ONLY when asked for. It is also possible to store large amounts of data, without affecting the website’s performance.
The data is stored in key/value pairs, and a web page can only access data stored by itself.
localStorage
stores data with no expiration date
sessionStorage
stores data for one session
Before using web storage, check browser support for localStorage and sessionStorage:
if(typeof(Storage)!=="undefined") { // Yes! localStorage and sessionStorage support! // Some code..... } else { // Sorry! No web storage support.. }
localStorage Object note
localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.
sessionStorage Object notes
sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window.
localStorage Object example set a local storage
<!DOCTYPE html>
HTML5 Application Cache
all major browsers, except Internet Explorer.
HTML5 introduces application cache, which means that a web application is cached, and accessible without an internet connection.
Application cache gives an application three advantages:
- Offline browsing - users can use the application when they’re offline
- Speed - cached resources load faster
- Reduced server load - the browser will only download updated/changed resources from the server
Cache Manifest Basics:
How to enable?
to enable application cache, include the manifest attribute in the document’s tag:
<!DOCTYPE HTML>
…
What is HTML5?
HTML5 will be the new standard for HTML.
The previous version of HTML, HTML 4.01, came in 1999. The web has changed a lot since then.
HTML5 is still a work in progress. However, the major browsers support many of the new HTML5 elements and APIs.
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
Reduce the need for external plugins (like Flash)
Better error handling
More markup to replace scripting
HTML5 should be device independent
The development process should be visible to the public
HTML5 - New Features
Some of the most interesting new features in HTML5:
The element for 2D drawing
The and elements for media playback
Support for local storage
New content-specific elements, like , , , ,
New form controls, like calendar, date, time, email, url, search
Browser Support for HTML5
HTML5 is not yet an official standard, and no browsers have full HTML5 support.
But all major browsers (Safari, Chrome, Firefox, Opera, Internet Explorer) continue to add new HTML5 features to their latest versions
HTML5 Video - How It Works
To show a video in HTML5, this is all you need:
Your browser does not support the video tag.
HTML5 Tag
- Defines a video or movie
- Defines multiple media resources for media elements, such as and
- Defines text tracks in mediaplayers
HTML5 autoplay Attribute
A video that will automatically start playing:
Your browser does not support the video tag.
Note:The autoplay attribute is a boolean attribute, and can be set in the following ways:
HTML5 controls Attribute
Note: The controls attribute is a boolean attribute, and can be set in the following ways:
HTML5 height Attribute
Differences Between HTML 4.01 and HTML5
The tag is new in HTML5.
Syntax:
HTML5 loop Attribute
The loop attribute is a boolean attribute.
When present, it specifies that the video will start over again, every time it is finished.
Syntax:
HTML5 poster Attribute
The poster attribute specifies an image to be shown while the video is downloading, or until the user hits the play button. If this is not included, the first frame of the video will be used instead.
HTML5 preload Attribute (no ie)
The preload attribute specifies if and how the author thinks that the video should be loaded when the page loads.
The preload attribute allows the author to provide a hint to the browser about what he/she thinks will lead to the best user experience. This attribute may be ignored in some instances.
Note: The preload attribute is ignored if autoplay is present.
HTML5 muted Attribute
muted attribute is supported in all major browsers, except Internet Explorer and Safari.
The muted attribute is a boolean attribute. When present, it specifies that the audio output of the video should be muted.
Note: The muted attribute is a boolean attribute, and can be set in the following ways:
HTML5 src Attribute
Your browser does not support the video tag.
HTML5 width Attribute
Note: Internet Explorer 8 and earlier versions, do not support the tag.
The width attribute is supported in all major browsers.
HTML5 Video + DOM
The HTML5 element also has methods, properties, and events.
There are methods for playing, pausing, and loading, for example. There are properties (e.g. duration, volume, seeking) that you can read or set. There are also DOM events that can notify you, for example, when the element begins to play, is paused, is ended, etc.
The examples below illustrate, in a simple way, how to address a element, read and set properties, and call methods.
HTML5 - Methods
play()
pause()
load()
canPlayType
HTML5 - Properties
currentSrc currrentTime videoWidth videoHeight duration ended error paused muted seeking volume height width
HTML5 - Events
play oause progress error timeupdate ended abort empty emptied waiting loadedmetadata
Audio on the Web
Until now, there has not been a standard for playing audio files on a web page.
Today, most audio files are played through a plug-in (like flash). However, different browsers may have different plug-ins.
HTML5 defines a new element which specifies a standard way to embed an audio file on a web page: the element.
HTML5 Audio - How It Works (code)
Your browser does not support the audio element.
HTML5 Canvas
The element is used to draw graphics, on the fly, on a web page.
What is Canvas?
The HTML5 element is used to draw graphics, on the fly, via scripting (usually JavaScript).
The element is only a container for graphics, you must use a script to actually draw the graphics.
A canvas is a drawable region defined in HTML code with height and width attributes.
Canvas has several methods for drawing paths, boxes, circles, characters, and adding images
Draw With JavaScript
The element has no drawing abilities of its own.
All drawing must be done inside a JavaScript
JavaScript uses the id to find the element
var c=document.getElementById(“myCanvas”);
create a context object:
var ctx=c.getContext(“2d”);
HTML5 Inline 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, indexed, scripted, and compressed
SVG images are scalable
SVG images can be printed with high quality at any resolution
SVG images are zoomable (and the image can be zoomed without degradation)
Embed SVG Directly Into HTML Pages
<!DOCTYPE html>
HTML5 - Using Geolocation
Longitude: “ + position.coords.longitude;
}
HTML5 - Using Geolocation
Handling Errors and Rejections
function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: x.innerHTML="User denied the request for Geolocation." break; case error.POSITION_UNAVAILABLE: x.innerHTML="Location information is unavailable." break; case error.TIMEOUT: x.innerHTML="The request to get user location timed out." break; case error.UNKNOWN_ERROR: x.innerHTML="An unknown error occurred." break; } }
Displaying the Result in a Map
function showPosition(position) { var latlon=position.coords.latitude+","+position.coords.longitude;
var img_url="http://maps.googleapis.com/maps/api/staticmap?center=" \+latlon+"&zoom=14&size=400x300&sensor=false";
document.getElementById(“mapholder”).innerHTML=””;
}
getCurrentPosition() Method - Return Data
coords.latitude - The latitude as a decimal number
coords.longitude - The longitude as a decimal number
coords.accuracy - The accuracy of position
coords.altitude - The altitude in meters above the mean sea level
coords.altitude - Accuracy The altitude accuracy of position
coords.heading - The heading as degrees clockwise from North
coords.speed - The speed in meters per second
timestamp - The date/time of the response
What is HTML5 Web Storage?
With HTML5, web pages can store data locally within the user’s browser.
Earlier, this was done with cookies. However, Web Storage is more secure and faster. The data is not included with every server request, but used ONLY when asked for. It is also possible to store large amounts of data, without affecting the website’s performance.
The data is stored in key/value pairs, and a web page can only access data stored by itself.
localStorage and sessionStorage
There are two new objects for storing data on the client:
localStorage - stores data with no expiration date
sessionStorage - stores data for one session
Before using web storage, check browser support for localStorage and sessionStorage:
if(typeof(Storage)!=="undefined") { // Yes! localStorage and sessionStorage support! // Some code..... } else { // Sorry! No web storage support.. }
localStorage Object
The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.
Example
localStorage.lastname=”Smith”;
document.getElementById(“result”).innerHTML=”Last name: “
+ localStorage.lastname;
example counts the number of times a user has clicked a button. In this code the value string is converted to a number to be able to increase the counter:
if (localStorage.clickcount) { localStorage.clickcount=Number(localStorage.clickcount)+1; } else { localStorage.clickcount=1; } document.getElementById("result").innerHTML="You have clicked the button " + localStorage.clickcount + " time(s).";
sessionStorage Object
if (sessionStorage.clickcount) { sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
} else {
sessionStorage.clickcount=1;
}
document.getElementById(“result”).innerHTML=”You have clicked the button “ + sessionStorage.clickcount + “ time(s) in this session.”;
What is Application Cache?
Application cache is supported in all major browsers, except Internet Explorer.
HTML5 introduces application cache, which means that a web application is cached, and accessible without an internet connection.
Application cache gives an application three advantages:
Offline browsing - users can use the application when they’re offline
Speed - cached resources load faster
Reduced server load - the browser will only download updated/changed resources from the server
HTML5 Cache Manifest Example
Application cache is supported in all major browsers, except Internet Explorer.
<!DOCTYPE HTML>
The content of the document……
Cache Manifest Basics
Every page with the manifest attribute specified will be cached when the user visits it. If the manifest attribute is not specified, the page will not be cached (unless the page is specified directly in the manifest file).
The recommended file extension for manifest files is: “.appcache”
A manifest file needs to be served with the correct MIME-type, which is “text/cache-manifest”. Must be configured on the web server.
…
The Manifest File
The manifest file is a simple text file, which tells the browser what to cache (and what to never cache).
The manifest file has three sections:
CACHE MANIFEST - Files listed under this header will be cached after they are downloaded for the first time
NETWORK - Files listed under this header require a connection to the server, and will never be cached
FALLBACK - Files listed under this header specifies fallback pages if a page is inaccessible
CACHE MANIFEST
The first line, CACHE MANIFEST, is required:
CACHE MANIFEST /theme.css /logo.gif /main.js The manifest file above lists three resources: a CSS file, a GIF image, and a JavaScript file. When the manifest file is loaded, the browser will download the three files from the root directory of the web site. Then, whenever the user is not connected to the internet, the resources will still be available
NETWORK
The NETWORK section below specifies that the file “login.asp” should never be cached, and will not be available offline:
NETWORK:
login.asp
An asterisk can be used to indicate that all other resources/files require an internet connection:
NETWORK:
*
FALLBACK
The FALLBACK section below specifies that “offline.html” will be served in place of all files in the /html5/ catalog, in case an internet connection cannot be established:
FALLBACK:
/html5/ /offline.html
Note: The first URI is the resource, the second is the fallback.
Updating the Cache
Once an application is cached, it remains cached until one of the following happens:
The user clears the browser’s cache
The manifest file is modified (see tip below)
The application cache is programmatically updated
Example - Complete Cache Manifest File
CACHE MANIFEST # 2012-02-21 v1.0.0 /theme.css /logo.gif /main.js
NETWORK:
login.asp
FALLBACK:
/html5/
/offline.html
Tip: Lines starting with a “#” are comment lines, but can also serve another purpose. An application’s cache is only updated when its manifest file changes. If you edit an image or change a JavaScript function, those changes will not be re-cached. Updating the date and version in a comment line is one way to make the browser re-cache your files.
Notes on Application Cache
Be careful with what you cache.
Once a file is cached, the browser will continue to show the cached version, even if you change the file on the server. To ensure the browser updates the cache, you need to change the manifest file.
Note: Browsers may have different size limits for cached data (some browsers have a 5MB limit per site).
HTML5 Web Workers
When executing scripts in an HTML page, the page becomes unresponsive until the script is finished.
A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.
Check Web Worker Support
Before creating a web worker, check whether the user’s browser supports it:
if(typeof(Worker)!=="undefined") { // Yes! Web worker support! // Some code..... } else { // Sorry! No Web Worker support.. }
Create a Web Worker File
Now, let’s create our web worker in an external JavaScript.
Here, we create a script that counts. The script is stored in the “demo_workers.js” file
var i=0;
function timedCount() { i=i+1; postMessage(i); setTimeout("timedCount()",500); }
timedCount();
The important part of the code above is the postMessage() method - which is used to posts a message back to the HTML page.
Note: Normally web workers are not used for such simple scripts, but for more CPU intensive tasks.
Create a Web Worker Object
Now that we have the web worker file, we need to call it from an HTML page.
The following lines checks if the worker already exists, if not - it creates a new web worker object and runs the code in “demo_workers.js”:
if(typeof(w)=="undefined") { w=new Worker("demo_workers.js"); } Then we can send and receive messages from the web worker.
Add an “onmessage” event listener to the web worker.
w.onmessage=function(event){
document.getElementById(“result”).innerHTML=event.data;
};
Terminate a Web Worker
When a web worker object is created, it will continue to listen for messages (even after the external script is finished) until it is terminated.
To terminate a web worker, and free browser/computer resources, use the terminate() method:
w.terminate();
HTML5 Server-Sent Events
Server-Sent Events - One Way Messaging
A server-sent event is when a web page automatically gets updates from a server.
This was also possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates come automatically.
Examples: Facebook/Twitter updates, stock price updates, news feeds, sport results, etc.
Receive Server-Sent Event Notifications
The EventSource object is used to receive server-sent event notifications:
var source=new EventSource("demo_sse.php"); source.onmessage=function(event) { document.getElementById("result").innerHTML+=event.data + ""; };
Check Server-Sent Events Support
In the tryit example above there were some extra lines of code to check browser support for server-sent events:
if(typeof(EventSource)!=="undefined") { // Yes! Server-sent events support! // Some code..... } else { // Sorry! No server-sent events support.. }
Server-Side Code Example
The server-side event stream syntax is simple. Set the “Content-Type” header to “text/event-stream”. Now you can start sending event streams.
Code in PHP (demo_sse.php):
Server-Side Code Example
The server-side event stream syntax is simple. Set the “Content-Type” header to “text/event-stream”. Now you can start sending event streams.
Code in ASP (VB) (demo_sse.asp):
The EventSource Object (list)
onopen - When a connection to the server is opened
onmessage - When a message is received
onerror - When an error occurs
HTML5 Input Types
color date datetime datetime-local email month number range search tel time url week
Input Type: color
<!DOCTYPE html>
Select your favorite color:
Input Type: date
<!DOCTYPE html>
Birthday:
Input Type: datetime
<!DOCTYPE html>
Birthday (date and time):
Input Type: datetime-local
<!DOCTYPE html>
Birthday (date and time):
Input Type: email
<!DOCTYPE html>
E-mail:
Input Type: month
<!DOCTYPE html>
Birthday (month and year):
Input Type: number
<!DOCTYPE html>
Quantity (between 1 and 5):
Input Type: range
<!DOCTYPE html>
Points:
Input Type: search
<!DOCTYPE html>
Search Google:
Input Type: time
<!DOCTYPE html>
Select a time:
Input Type: url
Add your homepage:
Input Type: week.
The week type allows the user to select a week and year.
<!DOCTYPE html>
Select a week:
HTML5 Tag
<!DOCTYPE html>
First name:
Last name:
HTML5 New Form Elements
HTML5 has the following new form elements:
Note: Not all major browsers support all the new form elements. However, you can already start using them; If they are not supported, they will behave as regular text fields.
HTML5 Element (exp)
he element specifies a list of pre-defined options for an element.
The element is used to provide an “autocomplete” feature on elements. Users will see a drop-down list of pre-defined options as they input data.
Use the element’s list attribute to bind it together with a element.
HTML5 Element (code)
HTML5 Element (code)
Username:
Encryption:
HTML5 Element (expl)
The purpose of the element is to provide a secure way to authenticate users.
The tag specifies a key-pair generator field in a form.
When the form is submitted, two keys are generated, one private and one public.
The private key is stored locally, and the public key is sent to the server. The public key could be used to generate a client certificate to authenticate the user in the future.
HTML5 Element
The element represents the result of a calculation (like one performed by a script).
<!DOCTYPE html>
0
100
+
=
New attributes for :
autocomplete
novalidate
New attributes for :
autocomplete autofocus form formaction formenctype formmethod formnovalidate formtarget height and width list min and max multiple pattern (regexp) placeholder required step
/ autocomplete Attribute (expl)
The autocomplete attribute specifies whether a form or input field should have autocomplete on or off.
When autocomplete is on, the browser automatically complete values based on values that the user has entered before.
Tip: It is possible to have autocomplete “on” for the form, and “off” for specific input fields, or vice versa.
Note: The autocomplete attribute works with and the following types: text, search, url, tel, email, password, datepickers, range, and color.
/ autocomplete Attribute (code)
First name:
Last name:
E-mail:
novalidate Attribute
The novalidate attribute is a boolean attribute.
When present, it specifies that the form-data (input) should not be validated when submitted.
E-mail:
autofocus Attribute
The autofocus attribute is a boolean attribute.
When present, it specifies that an element should automatically get focus when the page loads.
<!DOCTYPE html>
First name:
Last name:
form Attribute
The form attribute specifies one or more forms an element belongs to.
Tip: To refer to more than one form, use a space-separated list of form ids.
First name:
Last name:
formaction Attribute
The formaction attribute specifies the URL of a file that will process the input control when the form is submitted.
The formaction attribute overrides the action attribute of the element.
Note: The formaction attribute is used with type=”submit” and type=”image”.
First name:
Last name:
formenctype Attribute
formenctype Attribute
First name:
formmethod Attribute
The formmethod attribute defines the HTTP method for sending form-data to the action URL.
The formmethod attribute overrides the method attribute of the element.
Note: The formmethod attribute can be used with type=”submit” and type=”image”.
First name:
Last name:
formnovalidate Attribute
The novalidate attribute is a boolean attribute.
When present, it specifies that the element should not be validated when submitted.
The formnovalidate attribute overrides the novalidate attribute of the element.
Note: The formnovalidate attribute can be used with type=”submit”.
E-mail:
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.
The formtarget attribute overrides the target attribute of the element.
Note: The formtarget attribute can be used with type=”submit” and type=”image”.
First name:
Last name:
height and width Attributes
The height and width attributes specify the height and width of an element.
Note: The height and width attributes are only used with .
Tip: Always specify both the height and width attributes for images. If height and width are set, the space required for the image is reserved when the page is loaded. However, without these attributes, the browser does not know the size of the image, and cannot reserve the appropriate space to it. The effect will be that the page layout will change during loading (while the images load).
list Attribute
The list attribute refers to a element that contains pre-defined options for an element.
min and max Attributes
The min and max attributes specify the minimum and maximum value for an element.
Note: The min and max attributes works with the following input types: number, range, date, datetime, datetime-local, month, time and week.
Enter a date before 1980-01-01:
Enter a date after 2000-01-01:
Quantity (between 1 and 5):
multiple Attribute
The multiple attribute is a boolean attribute.
When present, it specifies that the user is allowed to enter more than one value in the element.
Note: The multiple attribute works with the following input types: email, and file.
Select images:
pattern Attribute
The pattern attribute specifies a regular expression that the element’s value is checked against.
Note: The pattern attribute works with the following input types: text, search, url, tel, email, and password.
Tip: Use the global title attribute to describe the pattern to help the user.
Tip: Learn more about regular expressions in our JavaScript tutorial.
Country code:
placeholder Attribute
The placeholder attribute specifies a short hint that describes the expected value of an input field (e.g. a sample value or a short description of the expected format).
The hint is displayed in the input field when it is empty, and disappears when the field gets focus.
Note: The placeholder attribute works with the following input types: text, search, url, tel, email, and password.
required Attribute
The required attribute is a boolean attribute.
When present, it specifies that an input field must be filled out before submitting the form.
Note: The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
Username:
step Attribute
The step attribute specifies the legal number intervals for an element.
Example: if step=”3”, legal numbers could be -3, 0, 3, 6, etc.
Tip: The step attribute can be used together with the max and min attributes to create a range of legal values.
Note: The step attribute works with the following input types: number, range, date, datetime, datetime-local, month, time and week.
HTML5 contenteditable Attribute
The contenteditable attribute specifies whether the content of an element is editable or not.
This is an editable paragraph.
true - Specifies that the element is editable
false - Specifies that the element is not editable
inherit - Specifies that the element is editable if its parent is
Window Event Attributes onafterprint
Script to be run after the document is printed
Window Event Attributes
onbeforeprint
Script to be run before the document is printed
Window Event Attributes
onbeforeonload
Script to be run before the document loads
Window Event Attributes
onblur
Script to be run when the window loses focus
Window Event Attributes
onerror
Script to be run when an error occur
Window Event Attributes
onfocus
Script to be run when the window gets focus
Window Event Attributes
onhaschange
Script to be run when the document has changed
Window Event Attributes
onload
Script to be run when the document loads
Window Event Attributes
onmessage
Script to be run when the message is triggered
Window Event Attributes
onoffline
Script to be run when the document goes offline
Window Event Attributes
ononline
Script to be run when the document comes online
Window Event Attributes
onpagehide
Script to be run when the window is hidden
Window Event Attributes
onpageshow
Script to be run when the window becomes visible
Window Event Attributes
onpopstate
Script to be run when the window’s history changes
Window Event Attributes
onredo
Script to be run when the document performs a redo
Window Event Attributes
onresize
Script to be run when the window is resized
Window Event Attributes
onstorage
Script to be run when a Web Storage area is updated
Window Event Attributes
onundo
Script to be run when the document performs an undo
Window Event Attributes
onunload
Script to be run when the user leaves the document
Form Events onblur
Script to be run when an element loses focus
Form Events onchange
Script to be run when an element changes
Form Events oncontextmenu
Script to be run when a context menu is triggered
Form Events onfocus
Script to be run when an element gets focus
Form Events onformchange
Script to be run when a form changes
Form Events onforminput
Script to be run when a form gets user input
Form Events oninput
Script to be run when an element gets user input
Form Events oninvalid
Script to be run when an element is invalid
Form Events onselect
Script to be run when an element is selected
Form Events onsubmit
Script to be run when a form is submitted
Keyboard Events onkeydown
Script to be run when a key is pressed down
Keyboard Events onkeypress
Script to be run when a key is pressed and released
Keyboard Events onkeyup
Script to be run when a key is released
Mouse Events onclick
Script to be run on a mouse click
Mouse Events ondblclick
Script to be run on a mouse double-click
Mouse Events ondrag
Script to be run when an element is dragged
Mouse Events ondragend
Script to be run at the end of a drag operation
Mouse Events ondragenter
Script to be run when an element has been dragged to a valid drop target
Mouse Events ondragleave
Script to be run when an element leaves a valid drop target
Mouse Events ondragover
Script to be run when an element is being dragged over a valid drop target
Mouse Events ondragstart
Script to be run at the start of a drag operation
Mouse Events ondrop
Script to be run when dragged element is being dropped
Mouse Events onmousedown
Script to be run when a mouse button is pressed
Mouse Events onmousemove
Script to be run when the mouse pointer moves
Mouse Events onmouseout
Script to be run when the mouse pointer moves out of an element
Mouse Events onmouseover
Script to be run when the mouse pointer moves over an element
Mouse Events onmouseup
Script to be run when a mouse button is released
Mouse Events onmousewheel
Script to be run when the mouse wheel is being rotated
Mouse Events onscroll
Script to be run when an element’s scrollbar is being scrolled
Media Events onabort
Script to be run on abort
Media Events oncanplay
Script to be run when a file is ready to start playing (when it has buffered enough to begin)
Media Events oncanplaythrough
Script to be run when a file can be played all the way to the end without pausing for buffering
Media Events ondurationchange
Script to be run when the length of the media changes
Media Events onemptied
Script to be run when something bad happens and the file is suddenly unavailable (like unexpectedly disconnects)
Media Events onended
Script to be run when the media has reach the end (a useful event for messages like “thanks for listening”)
Media Events onerror
Script to be run when an error occurs when the file is being loaded
Media Events onloadeddata
Script to be run when media data is loaded
Media Events onloadedmetadata
Script to be run when meta data (like dimensions and duration) are loaded
Media Events onloadstart
Script to be run just as the file begins to load before anything is actually loaded
Media Events onpause
Script to be run when the media is paused either by the user or programmatically
Media Events onplay
Script to be run when the media is ready to start playing
Media Events onplaying
Script to be run when the media actually has started playing
Media Events onratechange
Script to be run each time the playback rate changes (like when a user switches to a slow motion or fast forward mode)
Media Events onreadystatechange
Script to be run each time the ready state changes (the ready state tracks the state of the media data)
Media Events onseeked
Script to be run when the seeking attribute is set to false indicating that seeking has ended
Media Events onseeking
Script to be run when the seeking attribute is set to true indicating that seeking is active
Media Events onstalled
Script to be run when the browser is unable to fetch the media data for whatever reason
Media Events onsuspend
Script to be run when fetching the media data is stopped before it is completely loaded for whatever reason
Media Events ontimeupdate
Script to be run when the playing position has changed (like when the user fast forwards to a different point in the media)
Media Events onvolumechange
Script to be run each time the volume is changed which (includes setting the volume to “mute”)
Media Events onwaiting
Script to be run when the media has paused but is expected to resume (like when the media pauses to buffer more data)
HTML5 Audio/Video DOM canPlayType() Method
The canPlayType() method checks if the browser can play the specified audio/video type. The canPlayType() method can return one of the following values:
“probably” - the browser most likely supports this audio/video type
“maybe” - the browser might support this audio/video type
“” - (empty string) the browser does not support this audio/video type
myVid=document.createElement(‘video’);
isSupp=myVid.canPlayType(vidType+’;codecs=”‘+codType+’”’);
HTML5 Audio/Video DOM load() Method
The load() method re-loads the audio/video element.
The load() method is used to update the audio/video element after changing the source or other settings.
document. getElementById(“mp4_src”).src=”movie.mp4”;
document. getElementById(“ogg_src”).src=”movie.ogg”;
document. getElementById(“video1”).load();
HTML5 Audio/Video DOM play() Method The play() method is supported in all major browsers.
var myVideo=document.getElementById("video1"); function playVid() { myVideo.play(); } function pauseVid() { myVideo.pause(); }
HTML5 Audio/Video DOM pause() Method The pause() method halts (pauses) the currently playing audio or video.
var myVideo=document.getElementById("video1"); function playVid() { myVideo.play(); } function pauseVid() { myVideo.pause(); }
HTML5 Audio/Video DOM autoplay Property
The autoplay property is supported in all major browsers.
Note: This property is not supported in Internet Explorer 8 and earlier.
myVid=document.getElementById(“video1”);
myVid.autoplay=true;
myVid.load();
HTML5 Audio/Video DOM buffered Property
The buffered property returns a TimeRanges object.
The TimeRanges object represents the user’s buffered ranges of the audio/video.
A buffered range is a time-range of buffered audio/video. The user gets several buffered ranges if he/she skips in the audio/video.
myVid=document.getElementById(“video1”);
alert(“Start: “ + myVid.buffered.start(0)
+ “ End: “ + myVid.buffered.end(0));
HTML5 Audio/Video DOM controls Property
The controls property sets or returns if the browser should display standard audio/video controls.
Standard audio/video controls should include:
Play Pause Seeking Volume Fullscreen toggle (for video) Captions/Subtitles (when available) Track (when available)
myVid=document.getElementById(“video1”);
myVid.controls=true;
HTML5 Audio/Video DOM currentSrc Property
The currentSrc property returns the URL of the current audio/video.
If no audio/video is set, an empty string is returned.
myVid=document.getElementById(“video1”);
alert(myVid.currentSrc);
HTML5 Audio/Video DOM currentTime Property
The currentTime property sets or returns the current position (in seconds) of the audio/video playback.
When setting this property, the playback will jump to the specified position.
myVid=document.getElementById(“video1”);
myVid.currentTime=5;
HTML5 Audio/Video DOM duration Property
The duration property returns the length of the current audio/video, in seconds.
If no audio/video is set, NaN (Not-a-Number) is returned.
myVid=document.getElementById(“video1”);
alert(myVid.duration);
HTML5 Audio/Video DOM ended Property
The ended property returns if the playback of the audio/video has ended.
An audio/video has ended when the playback position is at the end of the audio/video.
myVid=document.getElementById(“video1”);
alert(myVid.ended);
HTML5 Audio/Video DOM loop Property
The loop property sets or returns if the audio/video should start playing over again when it is finished.
myVid=document.getElementById(“video1”);
myVid.loop=true;
HTML5 Audio/Video DOM muted Property
The muted property sets or returns if the audio/video should be muted (sound turned off).
Turn off sound for the video:
myVid=document.getElementById(“video1”);
myVid.muted=true;
HTML5 Audio/Video DOM networkState Property
The networkState property returns the current network state (activity) of the audio/video.
Get the current network state of the video:
myVid=document.getElementById(“video1”);
alert(myVid.networkState);
HTML5 Audio/Video DOM paused Property
The paused property returns if the audio/video is paused.
Check if the video is paused:
myVid=document.getElementById(“video1”);
alert(myVid.paused);
HTML5 Audio/Video DOM preload Property
The preload property sets or returns if the audio/video should start loading as soon as the page loads.
The preload property allows the author to provide a hint to the browser about what he/she thinks will lead to the best user experience. This attribute may be ignored in some instances.
myVid=document.getElementById(“video1”);
myVid.preload=”auto”;
HTML5 Audio/Video DOM readyState Property
The readyState property returns the current ready state of the audio/video.
The ready state indicates if the audio/video is ready to play or not.
Get the current ready state of the video:
myVid=document.getElementById(“video1”);
alert(myVid.readyState);
HTML5 Audio/Video DOM seekable Property
The seekable property returns a TimeRanges object.
The TimeRanges object represents ranges of the audio/video that are available for seeking for user.
A seekable range is a time-range of audio/video where the user can seek (move playback position) to.
For non-streaming videos it is often possible to seek anywhere in the video even before it has been buffered.
Get the first seekable range (part) of the video in seconds:
myVid=document.getElementById(“video1”);
alert(“Start: “ + myVid.seekable.start(0)
+ “ End: “ + myVid.seekable.end(0));
HTML5 Audio/Video DOM seeking Property
The seeking property returns if the user is currently seeking in the audio/video.
Seeking is when you move/skip to a new position in the audio/video.
Show if the user is currently seeking in the video:
myVid=document.getElementById(“video1”);
document.getElementById(“span1”).innerHTML=(“Seeking: “ + myVid.seeking);
HTML5 Audio/Video DOM src Property
The src property sets or returns the current source of the audio/video.
Change the source of the video:
myVid=document.getElementById(“video1”);
myVid.src=”movie.ogg”
HTML5 Audio/Video DOM volume Property
The volume property sets or returns the current volume of the audio/video.
Set video volume to 20%:
myVid=document.getElementById(“video1”);
myVid.volume=0.2;
HTML5 Audio/Video DOM canplay Event The canplay event occurs when the browser can start playing the specified audio/video. During the loading process of an audio/video, the following events occur, in this order: loadstart durationchange loadedmetadata loadeddata progress canplay canplaythrough
Alert that the video is ready to start playing:
myVid=document.getElementById(“video1”);
myVid.oncanplay=alert(“Can start playing video”);
HTML5 Audio/Video DOM canplaythrough Event
Definition and Usage
The canplaythrough event occurs when the browser estimates it can play through the specified audio/video without having to stop for buffering.
During the loading process of an audio/video, the following events occur, in this order:
loadstart
durationchange
loadedmetadata
loadeddata
progress
canplay
canplaythrough
Alert that the video can be played all the way through, without stopping:
myVid=document.getElementById(“video1”);
myVid.oncanplaythrough=alert(“Can play through video without stopping”);
HTML5 Audio/Video DOM durationchange Event
The durationchange event occurs when the duration data of the specified audio/video is changed.
When an audio/video is loaded, the duration will change from “NaN” to the actual duration of the audio/video.
During the loading process of an audio/video, the following events occur, in this order:
loadstart
durationchange
loadedmetadata
loadeddata
progress
canplay
canplaythrough
myVid=document.getElementById(“video1”);
myVid.ondurationchange=alert(“The video duration has changed”);
HTML5 Audio/Video DOM loadeddata Event The loadeddata event occurs when data for the current frame is loaded, but not enough data to play next frame of the specified audio/video. During the loading process of an audio/video, the following events occur, in this order: loadstart durationchange loadedmetadata loadeddata progress canplay canplaythrough
Alert that data for the current frame is available:
myVid=document.getElementById(“video1”);
myVid.onloadeddata=alert(“Browser has loaded the current frame”);
HTML5 Audio/Video DOM loadedmetadata Event
myVid=document.getElementById(“video1”);
myVid.onloadedmetadata=alert(“Meta data for video loaded”);
The loadedmetadata event occurs when meta data for the specified audio/video has been loaded.
Meta data for audio/video consists of: duration, dimensions (video only) and text tracks. During the loading process of an audio/video, the following events occur, in this order: loadstart durationchange loadedmetadata loadeddata progress canplay canplaythrough
HTML5 Audio/Video DOM loadstart Event
The loadstart event occurs when the browser starts looking for the specified audio/video. This is when the loading process starts.
During the loading process of an audio/video, the following events occur, in this order: loadstart durationchange loadedmetadata loadeddata progress canplay canplaythrough
Alert that the video is starting to load:
myVid=document.getElementById(“video1”);
myVid.onloadstart=alert(“Starting to load video”);
HTML5 Audio/Video DOM progress Event The progress event occurs when the browser is downloading the specified audio/video. During the loading process of an audio/video, the following events occur, in this order: loadstart durationchange loadedmetadata loadeddata progress canplay canplaythrough
myVid=document.getElementById(“video1”);
myVid.onprogress=alert(“Downloading video”);
HTML5 canvas fillStyle Attribute
HTML5 canvas strokeStyle Attribute
The strokeStyle attribute specifies the color of the selected drawing property.
HTML5 canvas lineCap Attribute
The lineCap attribute specifies the “pencil cap” of the drawing property.
HTML5 canvas lineJoin Attribute
The lineJoin attribute specifies how to display the corners when drawing lines.
HTML5 canvas lineWidth Attribute
The lineWidth attribute specifies the width of the stroke of the selected drawing property.
HTML5 canvas miterLimit Attribute
The miterLimit attribute works only if the lineJoin attribute is “miter”.
The miter is the distance between the inner corner and the outer corner in a line.
HTML5 canvas shadowColor Attribute
The shadowColor attribute specifies the color of the shadow.
The shadow is adjusted by using the shadowOffsetX, shadowOffsetY, and the shadowBlur attributes.
HTML5 canvas shadowOffsetX Attribute
The shadowOffsetX attribute specifies the left and right position of the shadow.
HTML5 canvas shadowOffsetY Attribute
The shadowOffsetY attribute specifies the vertical position of the shadow.
HTML5 canvas shadowBlur Attribute
HTML5 canvas createLinearGradient Method
The createLinearGradient method creates a gradient object that changes from one color to another.
You can specify how and where these changes will take place, using the coordinate parameters.
The x0 and y0 parameters represents the start coordinates of the gradient.
The x1 and y1 parameters represents the end coordinates of the gradient.
Use the addColorStop() method to specify a color, and where to position the color in the gradient.
The gradient can be used to draw/fill rectangles, circles, lines etc.
HTML5 canvas createPattern Method
The createPattern method uses an object to create a pattern to use on the canvas.
The object can be an image, a video, or another canvas element.
The pattern can be used to draw/fill rectangles, circles, lines etc.
HTML5 canvas createRadialGradient Method
The createRadialGradient method creates a gradient object that makes a circle using the specified parameters.
The x0 and y0 represents the coordinates, of the start circle, where r0 represents the radius.
The x1 and y1 represents the coordinates of the end circle, where r1 represents the radius.
Use the addColorStop() method to specify a color, and where to position the color in the gradient.
The gradient can be used to draw/fill rectangles, circles, lines etc.
var canvas=document.getElementById(“myCanvas”);
var ctx=canvas.getContext(“2d”);
var grd=ctx.createRadialGradient(100,50,5,60,50,50);
grd.addColorStop(0,”red”);
grd.addColorStop(1,”white”);
ctx.fillStyle=grd;
ctx.fillRect(0,0,150,100);
HTML5 canvas addColorStop Method
The addColorStop method specifies a color, and where to position the color in a gradient object.
The addColorStop method is used togheter with the createLinearGradient method or the createRadialrGradient.
var canvas=document.getElementById(“myCanvas”);
var ctx=canvas.getContext(“2d”);
var grd=ctx.createLinearGradient(0,0,150,0);
grd.addColorStop(0.3,”red”);
grd.addColorStop(0.7,”green”);
ctx.fillStyle=grd;
ctx.fillRect(0,0,150,100);
HTML5 canvas fillRect Method
The fillRect method specifies a rectangle filled with a specified color.
Use the fillStyle attribute to specify a color, black is default and will be used if the fillStyle attribute is not specified.
The fillRect method takes four parameters (x,y,w,h).
The first two parameters represents the x and y coordinates of where to place the rectangle in the canvas.
The last two parameters represents the size (width and height) of the rectangle.
HTML5 canvas strokeRect Method
The strokeRect method creates a rectangle.
Use the strokeStyle attribute to specify a color, black is default and will be used if the strokeStyle attribute is not specified.
The strokeRect method takes four parameters (x,y,w,h).
The first two parameters represents the x and y coordinates of where to place the rectangle in the canvas.
The last two parameters represents the size (width and height) of the rectangle.
HTML5 canvas clearRect Method
The clearRect method clears all pixels inside the specified rectangle.
The clearRect method takes four parameters (x,y,w,h).
The first two parameters represents the x and y coordinates of where to begin erasing in the canvas.
The last two parameters represents the size (width and height) of the erasing rectangle.
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.fillStyle="red"; ctx.fillRect(0,0,300,150); ctx.fillStyle="yellow"; ctx.fillRect(40,40,150,100); ctx.strokeRect(30,10,150,100); ctx.clearRect(20,20,100,50);
HTML5 canvas beginPath Method
The beginPath method clears the current path and specifies the beginning of a new path.
Use the moveTo(), lineTo(), quadricCurveTo, bezierCurveTo, arcTo, and arc(), to create paths.
Use the stroke() and fill() methods to draw the path on the canvas.
HTML5 canvas moveTo Method
The moveTo method moves the path to the specified point in the canvas, without creating a line.
The moveTo method takes two parameters, the x an y coordinates.
Draw a path, shaped as the letter T:
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.beginPath(); ctx.moveTo(50,20); ctx.lineTo(50,100); ctx.moveTo(20,20); ctx.lineTo(80,20); ctx.stroke();
HTML5 canvas closePath Method
The closePath method draws a line from the path’s current point to the starting point.
Use the stroke() method to draw the path on the canvas.
Use the fill() method fill the path, the path will be filled with the color selected by the fillStyle attribute, black is default.
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.beginPath(); ctx.moveTo(20,20); ctx.lineTo(20,100); ctx.lineTo(70,100); ctx.closePath(); ctx.stroke();
HTML5 canvas lineTo Method
The lineTo method creates a line from the path’s current point to the specified point in the canvas.
The lineTo method takes two parameters, the x and y coordinates.
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.beginPath(); ctx.moveTo(20,20); ctx.lineTo(20,100); ctx.lineTo(70,100); ctx.stroke();
HTML5 canvas rect Method
The rect method creates a rectangle.
Use the stroke() or fill() methods to draw the rectangle on the canvas.
The rect method takes four parameters (x,y,w,h).
The first two parameters represents the x and y coordinates of where to place the rectangle in the canvas.
The last two parameters represents the size (width and height) of the rectangle.
var c=document.getElementById(“myCanvas”);
var ctx=c.getContext(“2d”);
ctx.rect(20,20,150,100);
ctx.stroke();
HTML5 canvas fill Method
The fill method fills the current path, with the color set by the fillStyle attribute, black is default.
If the current point is not the same as the start point, in the path, the fill method will complete the path by adding a line from the last point, to the startpoint of the path, like the closePath() method.
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.rect(20,20,150,100); ctx.fillStyle="red"; ctx.fill();
HTML5 canvas stroke Method
The stroke method strokes the current path, with the color set by the strokeStyle attribute, black is default.
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.moveTo(75,20); ctx.lineTo(20,20); ctx.lineTo(20,100); ctx.lineTo(75,100); ctx.moveTo(20,60); ctx.lineTo(60,60); ctx.strokeStyle="orange"; ctx.stroke();
HTML5 canvas clip Method
The clip method creates an area in the canvas, described with the different path methods, and this area is the only visible area in the canvas.
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.rect(10,15,200,75); ctx.clip(); ctx.fillStyle="lightblue"; ctx.fillRect(0,0,300,150) ctx.fillStyle="red"; ctx.font="30px Arial"; ctx.fillText("Hello world", 10,30);
HTML5 canvas quadraticCurveTo Method
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.beginPath(); ctx.moveTo(20,20); ctx.quadraticCurveTo(20,100,200,20); ctx.stroke();
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.beginPath(); ctx.moveTo(20,20); ctx.quadraticCurveTo(20,100,200,20); ctx.stroke();
HTML5 canvas bezierCurveTo Method
The bezierCurveTo method creates a line from the path’s current point to the specified point, via two controlpoints.
The bezierCurveTo method takes six parameters, the x and y coordinates for the first controlpoint, the x and y coordinates for the second controlpoint, and the x and y coordinates for the line’s destination.
var c=document.getElementById(“myCanvas”);
var ctx=c.getContext(“2d”);
ctx.beginPath();
ctx.moveTo(20,20);
ctx.bezierCurveTo(20,100,200,100,200,20);
ctx.stroke();
HTML5 canvas isPointInPath Method
The isPointInPath method returns a Boolean (true/false) value whether or not the specified point is in the current path.
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.rect(20,20,150,100); if (ctx.isPointInPath(20,50)) { ctx.stroke(); };
HTML5 canvas scale Method
The scale method scales the drawings, bigger or smaller.
You can scale the width or the height or both, by using the two parameters
If you scale both width and height two times (2,2) all drawings, from now on, will be twice as wide and twice as high as you specify
Also, the positioning will be scaled. If you scale (2,2), drawings will be positioned twice as far from the left, and top, of the canvas.
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.strokeRect(5,5,25,15); ctx.scale(5,5); ctx.strokeRect(5,5,25,15);
HTML5 canvas rotate Method
The rotate method rotates the canvas.
The rotation is done in an angle from the canvas’ position 0,0
var c=document.getElementById(“myCanvas”);
var ctx=c.getContext(“2d”);
ctx.rotate(20*Math.PI/180);
ctx.fillRect(50,50,100,50);
HTML5 canvas translate Method
The translate method moves the canvas to the given position.
The canvas itself will not change position, but all drawings done after the translate() method is moved
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.fillRect(10,10,100,50); ctx.translate(70,70); ctx.fillRect(10,10,100,50);
HTML5 canvas transform Method
The transform method uses a matrix to change the form of the canvas.
The transform method lets you scale, rotate, move, and skew the canvas.
The transformation will only affect drawings made after the transform method is called.
The transform method takes six parameters, representing the matrix.
The transform method behaves relatively to other transformations made by the rotate, scale, or translate methods. I.e. if you have allready set your drawing to scale by two, and the transform method scales your drawings by two, your drawings will now scale by four.
Tip: Check out the setTransform method, it does not behave relatively to other transformations.
HTML5 canvas setTransform Method
The transform method uses a matrix to change the form of the canvas.
The transform method lets you scale, rotate, move, and skew the canvas.
The transformation will only affect drawings made after the transform method is called.
The transform method takes six parameters, representing the matrix.
ctx. font=”30px Arial”;
ctx. fillText(“Transform”,10,30);
ctx. setTransform(0.93,0.3,-0.3,0.93,0,0);
ctx. fillStyle=”lightblue”;
ctx. fillRect(0,0,250,100)
HTML5 canvas font Attribute
The font attribute allows you to specify font properties of the text written on the canvas.
The font attribute uses the same syntax as the CSS font property.
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.font="30px Arial"; ctx.fillText("Hello World",10,50);
HTML5 canvas textAlign Attribute
The textAlign attribute is used to align text on the canvas.c
Use the fillText() or the strokeText() methods to place the text on the canvas.
The text will be aligned relatively from where you place the text.
If you place a text at position 150,75 and set textAlign=”right”, the text will end at position 150,75.
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.textAlign="right"; ctx.fillText("Hello World",150,75);
HTML5 canvas textBaseline Attribute
The textBaseline attribute is used to vertically align text on the canvas.
Imagine there are lines running through the letters:
The fillText() and strokeText() methods will use these lines when positioning the text.
The different attributevalues will produce this output:
ctx. textBaseline=”bottom”;
ctx. fillText(“Bottom”,10,50);
ctx. textBaseline=”middle”;
ctx. fillText(“Middle”,97,50);
ctx. textBaseline=”top”;
ctx. fillText(“Top”,175,50);
HTML5 canvas fillText Method
The fillText method specifies a text filled with a specified color.
Use the fillStyle attribute to specify a color, black is default and will be used if the fillStyle attribute is not specified.
The fillText method takes four parameters (text,x,y,maxWidth).
The first parameter represents the actual text.
The next two parameters represents the x and y coordinates of where to place the text on the canvas.
The last parameter is optional and represents the maximum width of the text, if the text is wider than the maxWidth the text will be displayd with a smaller font.
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.font="30px Arial"; ctx.fillText("Hello World",10,50);
HTML5 canvas strokeText Method
The strokeText method species text on the canvas, drawn wit the specified color.
The strokeText method does not fill the letters with color, only the “borders”.
Use the strokeStyle attribute to specify a color, black is default and will be used if the strokeStyle attribute is not specified.
The strokeText method takes four parameters (text,x,y,maxWidth).
The first parameter represents the actual text.
The next two parameters represents the x and y coordinates of where to place the text on the canvas.
The last parameter is optional and represents the maximum width of the text, if the text is wider than the maxWidth the text will be displayd with a smaller font.
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.font="30px Arial"; ctx.strokeText("Hello World",10,50);
HTML5 canvas measureText Method
The measureText method returns an object, with one attribute: width.
The width attribute returns the width of the text, in pixels.
Can be useful if you must know the width of a text before writing it on the canvas.
var c=document.getElementById(“myCanvas”);
var ctx=c.getContext(“2d”);
var txt=”Hello World”
ctx.font=”30px Arial”;
ctx.fillText(“width:” + ctx.measureText(txt).width,10,50)
ctx.fillText(txt,10,100);
HTML5 canvas imagedata width Attribute
The width attribute specifies the width of the imagedata object, in pixels.
var ctx=c.getContext("2d"); var imgData=ctx.createImageData(50,50); for (i=0; i<imgData.width*imgData.height*4;i+=4) { imgData.data[i+0]=255; imgData.data[i+1]=0; imgData.data[i+2]=0; imgData.data[i+3]=255; } ctx.putImageData(imgData,10,10);
HTML5 canvas imagedata height Attribute
The height attribute specifies the height of the imagedata object, in pixels.
ar ctx=c.getContext("2d"); var imgData=ctx.createImageData(50,50); for (i=0; i<imgData.width*imgData.height*4;i+=4) { imgData.data[i+0]=255; imgData.data[i+1]=0; imgData.data[i+2]=0; imgData.data[i+3]=255; } ctx.putImageData(imgData,10,10);
HTML5 canvas imagedata data Attribute
The data attribute represents an array containing information of every pixel of an imagedata object.
For every pixel in the imagedata object there are 4 pieces of information, the rgba values:
- The color red (0-255)
- The color green (0-255)
- The color blue (0-255)
- The alpha strength (0-255) where 0 is transparent and 255 is fully visible
The information is held in an array, and since the array contains 4 pieces of information of every pixel, the array’s size is 4 times the size of the rectangle: widthheight4.
You can change the information in the array, and put the new drawings back on the canvas, using the putImageData method.
var ctx=c.getContext("2d"); var imgData=ctx.createImageData(50,50); for (i=0; i
HTML5 canvas drawImage Method
The drawImage method is used when you want to use images on the canvas.
The drawImage method can also draw parts of an image, and/or increase/reduce the image size.
The drawImage method can take up to nine parameters, depending on what you want to do with the image.
The image object can be an image, a video, or another canvas element.
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); var img=document.getElementById("scream"); ctx.drawImage(img,90,130,50,60,10,10,50,60);
HTML5 canvas createImageData Method
The createImageData method specifies a new blank imagedata object.
All pixels of the new object has the default value transparent black, rgba(0,0,0,0).
The createImageData method can take two parameters which specifies the width and heigh.
The createImageData method can also take only one parameter, imgData, which will also create a new blank imagedata object where all the pixels are transparent black, but the width and height will be the same as the passed imageData object’s width and height.
For every pixel in the imagedata object there are 4 pieces of information, the rgba values:
1. The color red (0-255)
2. The color green (0-255)
3. The color blue (0-255)
4. The alpha strength (0-255) where 0 is transparent and 255 is fully visible
The information is held in an array, and since the array contains 4 pieces of information of every pixel, the array’s size is 4 times the size of the rectangle: widthheight4.
The array containing the information is stored in the .data property of the imagedata object.
You can change the information in the array, and put the new drawings back on the canvas, using the putImageData method.
var ctx=c.getContext("2d"); var imgData=ctx.createImageData(50,50); for (i=0; i
HTML5 canvas getImageData Method
The getImageData method creates a new imagedata object.
All pixels of the new imagedata object has the same rgba values as the specified parts of the canvas.
With the getImageData method you can read the pixels one by one.
The getImageData method takes four parameters, specifying a rectangle of the canvas (x,y,width,height).
The imagedata object is not a picture, it specifies a part (rectangle) of the canvas, and holds information of every pixel inside that rectangle.
For every pixel in the imagedata object there are 4 pieces of information, the rgba values:
1. The color red (0-255) 2. The color green (0-255) 3. The color blue (0-255) 4. The alpha strength (0-255) where 0 is invisible and 255 is fully visible
The information is held in an array, and since the array contains 4 pieces of information of every pixel, the array’s size is 4 times the size of the rectangle: widthheight4
The array containing the information is stored in the .data property of the imagedata object.
You can change the information in the array, and put the new drawings back onto the canvas, using the putImageData method.
Tip: For a demonstration of what you can do with the getImageData method, take a look at the example at the bottom of this page.
... ctx.fillStyle="red"; ctx.fillRect(10,10,50,50); var imgData=ctx.getImageData(30,30,50,50); for (i=0; i
HTML5 canvas putImageData Method
The putImageData method is used to put the data from an imagedata object onto the canvas.
The putImageData method can take three or seven parameters, three if the drawings should be the same size and shape as the imageData, and seven if you want to specify what part of the drawings that should be placed onto the canvas.
Read about the getImageData method, to learn how to manipulate the pixels.
Tip: For a demonstration of what you can do with the putImageData method, take a look at the example at the bottom of this page.
... ctx.fillStyle="red"; ctx.fillRect(10,10,50,50); var imgData=ctx.getImageData(30,30,50,50); for (i=0; i
HTML5 canvas globalAlpha Attribute
The globalAlpha attribute specifies the transparency of the drawings.
The globalAlpha attribute value can be a number between 0 and 1.
0=full transparency, 1=no transparency.
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.fillStyle="red"; ctx.fillRect(20,20,75,50); ctx.fillStyle="blue"; ctx.globalAlpha=0.2; ctx.fillRect(50,50,75,50);
tabindex attribute
Press the Tab key repeatedly on your keyboard
while on a web page, and you’ll see different page elements become highlighted
First Item Active
Third Item Active
Second Item Active
code of how to get an element with id of “about-text”
document.getElementById(“about-text”)
Hiding elements
Red Fox
Vulpes vulpes
In HTML 4.01, the meta element looked like this
In HTML5 5, the meta element looks like this
4 –
5 –
Microdata
uses a set of global attributes that may be used to add additional
semantic structure to the content on a page.
No More Types for Scripts and Links
——HTML4—–
—–HTML5——
how to make content of an element editable
- Break mechanical cab driver.
Drive to abandoned factory - Watch video of self
Internet Explorer and HTML5
In order to ensure that the new HTML5 elements render correctly as block level elements, it’s necessary at this time to style them as such.
header, footer, article, section, nav, menu, hgroup {
display: block;
}
Unfortunately, Internet Explorer will still ignore these stylings, because it has no clue what, as an example, the header element even is. Luckily, there is an easy fix:
document. createElement(“article”);
document. createElement(“footer”);
document. createElement(“header”);
document. createElement(“hgroup”);
document. createElement(“nav”);
document. createElement(“menu”);
Required Attribute
Autofocus Attribute
Regular Expressions
the new pattern attribute, we can insert a regular expression directly into our markup
Create a Username: Go
Detect Support for Attributes
semantic tags explanation old vs HTML5
semantics via distribution , , , ,, semantics via HTML5 , , , , ,
list HTML5 semantic tags
article aside figcaption figure footer header hgroup mark nav section time