HTML 5
HTML 5
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.
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
<!DOCTYPE html>
html>
of
the
document</title>
content
of
the
document......
</html>
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
Defines sound content Defines bold text Specifies the base URL/target for all relative URLs in a document Not supported in HTML5. Deprecated in HTML 4.01. Specifies a default color, size, and font for all text in a document Isolates a part of text that might be formatted in a different direction from other text outside it Overrides the current text direction Not supported in HTML5. Defines big text Defines a section that is quoted from another source Defines the document's body Defines a single line break Defines a clickable button Used to draw graphics, on the fly, via scripting (usually JavaScript) Defines a table caption Not supported in HTML5. Deprecated in HTML 4.01. Defines centered text Defines the title of a work Defines a piece of computer code Specifies column properties for each column within a <colgroup> element Specifies a group of one or more columns in a table for formatting Defines a command button that a user can invoke Specifies a list of pre-defined options for input controls Defines a description of an item in a definition list Defines text that has been deleted from a document Defines additional details that the user can view or hide Defines a definition term Not supported in HTML5. Deprecated in HTML 4.01. Defines a directory list
<bdi>New
<bdo> <big> <blockquote> <body> <br> <button> <canvas>New <caption> <center> <cite> <code> <col> <colgroup> <command>New <datalist>New <dd> <del> <details>New <dfn> <dir>
<div> <dl> <dt> <em> <embed>New <fieldset> <figcaption>New <figure>New <font> <footer>New <form> <frame> <frameset> <h1> to <h6> <head> <header>New <hgroup>New <hr> <html> <i> <iframe> <img> <input> <ins> <kbd> <keygen>New
Defines a section in a document Defines a definition list Defines a term (an item) in a definition list Defines emphasized text Defines a container for an external (non-HTML) application Groups related elements in a form Defines a caption for a <figure> element Specifies self-contained content Not supported in HTML5. Deprecated in HTML 4.01. Defines font, color, and size for text Defines a footer for a document or section Defines an HTML form for user input Not supported in HTML5. Defines a window (a frame) in a frameset Not supported in HTML5. Defines a set of frames Defines HTML headings Defines information about the document Defines a header for a document or section Groups heading (<h1> to <h6>) elements Defines a thematic change in the content Defines the root of an HTML document Defines a part of text in an alternate voice or mood Defines an inline frame Defines an image Defines an input control Defines a text that has been inserted into a document Defines keyboard input Defines a key-pair generator field (for forms)
Defines a label for an <input> element Defines a caption for a <fieldset>, < figure>, or <details> element Defines a list item Defines the relationship between a document and an external resource (most used to link to style sheets) Defines a client-side image-map Defines marked/highlighted text Defines a list/menu of commands Defines metadata about an HTML document Defines a scalar measurement within a known range (a gauge) Defines navigation links Not supported in HTML5. Defines an alternate content for users that do not support frames Defines an alternate content for users that do not support client-side scripts Defines an embedded object Defines an ordered list Defines a group of related options in a drop-down list Defines an option in a drop-down list Defines the result of a calculation Defines a paragraph Defines a parameter for an object Defines preformatted text Represents the progress of a task Defines a short quotation Defines what to show in browsers that do not support ruby annotations Defines an explanation/pronunciation of characters (for East Asian typography) Defines a ruby annotation (for East Asian typography) Defines text that is no longer correct
<map> <mark>New <menu> <meta> <meter>New <nav>New <noframes> <noscript> <object> <ol> <optgroup> <option> <output>New <p> <param> <pre> <progress>New <q> <rp>New <rt>New <ruby>New <s>
<samp> <script> <section>New <select> <small> <source>New <span> <strike> <strong> <style> <sub> <summary>New <sup> <table> <tbody> <td> <textarea> <tfoot> <th> <thead> <time>New <title> <tr> <track>New <tt> <u>
Defines sample output from a computer program Defines a client-side script Defines a section in a document Defines a drop-down list Defines smaller text Defines multiple media resources for media elements (<video> and <audio>) Defines a section in a document Not supported in HTML5. Deprecated in HTML 4.01. Defines strikethrough text Defines important text Defines style information for a document Defines subscripted text Defines a visible heading for a <details> element Defines superscripted text Defines a table Groups the body content in a table Defines a cell in a table Defines a multiline input control (text area) Groups the footer content in a table Defines a header cell in a table Groups the header content in a table Defines a date/time Defines a title for the document Defines a row in a table Defines text tracks for media elements (<video> and <audio>) Not supported in HTML5. Defines teletype text Defines text that should be stylistically different from normal text
Defines an unordered list Defines a variable Defines a video or movie Defines a possible line-break
Ordered by Function
New : New tags in HTML5. Tag Basic <!DOCTYPE> <html> <title> <body> <h1> to <h6> <p> <br> <hr> <!--...--> Formatting <acronym> <abbr> <address> Not supported in HTML5. Defines an acronym Defines an abbreviation Defines contact information for the author/owner of a document/article Defines bold text Isolates a part of text that might be formatted in a different direction from other text outside it Overrides the current text direction Defines the document type Defines an HTML document Defines a title for the document Defines the document's body Defines HTML headings Defines a paragraph Inserts a single line break Defines a thematic change in the content Defines a comment Description
<b> <bdi>New
<bdo>
Not supported in HTML5. Defines big text Defines a section that is quoted from another source Not supported in HTML5. Deprecated in HTML 4.01. Defines centered text Defines the title of a work Defines a piece of computer code Defines text that has been deleted from a document Defines a definition term Defines emphasized text Not supported in HTML5. Deprecated in HTML 4.01. Defines font, color, and size for text Defines a part of text in an alternate voice or mood Defines a text that has been inserted into a document Defines keyboard input Defines marked/highlighted text Defines a scalar measurement within a known range (a gauge) Defines preformatted text Represents the progress of a task Defines a short quotation Defines what to show in browsers that do not support ruby annotations Defines an explanation/pronunciation of characters (for East Asian typography) Defines a ruby annotation (for East Asian typography) Defines text that is no longer correct Defines sample output from a computer program Defines smaller text Not supported in HTML5. Deprecated in HTML 4.01. Defines strikethrough text
<i> <ins> <kbd> <mark>New <meter>New <pre> <progress>New <q> <rp>New <rt>New
<strong> <sub> <sup> <time>New <tt> <u> <var> <wbr>New Forms <form> <input> <textarea> <button> <select> <optgroup> <option> <label> <fieldset> <legend> <datalist>New <keygen>New <output>New Frames <frame> <frameset> <noframes>
Defines important text Defines subscripted text Defines superscripted text Defines a date/time Not supported in HTML5. Defines teletype text Defines text that should be stylistically different from normal text Defines a variable Defines a possible line-break
Defines an HTML form for user input Defines an input control Defines a multiline input control (text area) Defines a clickable button Defines a drop-down list Defines a group of related options in a drop-down list Defines an option in a drop-down list Defines a label for an <input> element Groups related elements in a form Defines a caption for a <fieldset>, < figure>, or <details> element Specifies a list of pre-defined options for input controls Defines a key-pair generator field (for forms) Defines the result of a calculation
Not supported in HTML5. Defines a window (a frame) in a frameset Not supported in HTML5. Defines a set of frames Not supported in HTML5. Defines an alternate content for users that do not support frames
<iframe> Images <img> <map> <area> <canvas>New <figcaption>New <figure>New Audio/Video <audio>New <source>New
Defines an image Defines a client-side image-map Defines an area inside an image-map Used to draw graphics, on the fly, via scripting (usually JavaScript) Defines a caption for a <figure> element Specifies self-contained content
Defines sound content Defines multiple media resources for media elements (<video> and <audio>) Defines text tracks for media elements (<video> and <audio>) Defines a video or movie
Defines a hyperlink Defines the relationship between a document and an external resource (most used to link to style sheets) Defines navigation links
Defines an unordered list Defines an ordered list Defines a list item Not supported in HTML5. Deprecated in HTML 4.01. Defines a directory list Defines a definition list Defines a term (an item) in a definition list Defines a description of an item in a definition list
<menu> <command>New Tables <table> <caption> <th> <tr> <td> <thead> <tbody> <tfoot> <col> <colgroup> Style/Sections <style> <div> <span> <header>New <footer>New <hgroup>New <section>New <article>New <aside>New <details>New <summary>New Meta Info
Defines a list/menu of commands Defines a command button that a user can invoke
Defines a table Defines a table caption Defines a header cell in a table Defines a row in a table Defines a cell in a table Groups the header content in a table Groups the body content in a table Groups the footer content in a table Specifies column properties for each column within a <colgroup> element Specifies a group of one or more columns in a table for formatting
Defines style information for a document Defines a section in a document Defines a section in a document Defines a header for a document or section Defines a footer for a document or section Groups heading (<h1> to <h6>) elements Defines a section in a document Defines an article Defines content aside from the page content Defines additional details that the user can view or hide Defines a visible heading for a <details> element
Defines information about the document Defines metadata about an HTML document Specifies the base URL/target for all relative URLs in a document Not supported in HTML5. Deprecated in HTML 4.01. Specifies a default color, size, and font for all text in a document
Programming <script> <noscript> Defines a client-side script Defines an alternate content for users that do not support client-side scripts Not supported in HTML5. Deprecated in HTML 4.01. Defines an embedded applet Defines a container for an external (non-HTML) application Defines an embedded object Defines a parameter for an object
<applet>
contenteditableNew contextmenuNew
hiddenNew id
lang spellcheckNew
Specifies the language of the element's content Specifies whether the element is to have its spelling and grammar checked or not Specifies an inline CSS style for an element Specifies the tabbing order of an element Specifies extra information about an element Specifies whether an element's value are to be translated when the page is localized, or not.
onofflineNew ononlineNew onpagehideNew onpageshowNew onpopstateNew onredoNew onresizeNew onstorageNew onundoNew onunload
script Script to be run when the document goes offline script Script to be run when the document comes online script Script to be run when the window is hidden script Script to be run when the window becomes visible script Script to be run when the window's history changes script Script to be run when the document performs a redo script Fires when the browser window is resized script Script to be run when a Web Storage area is updated script Script to be run when the document performs an undo script Fires once a page has unloaded (or the browser window has been closed)
Form Events
Events triggered by actions inside a HTML form (applies to almost all HTML elements, but is most used in form elements):
Attribute onblur onchange oncontextmenuNew onfocus onformchangeNew onforminputNew oninputNew oninvalidNew onreset Value Description script script script script script script script script script Fires the moment that the element loses focus Fires the moment when the value of the element is changed Script to be run when a context menu is triggered Fires the moment when the element gets focus Script to be run when a form changes Script to be run when a form gets user input Script to be run when an element gets user input Script to be run when an element is invalid Fires when the Not supported in HTML5 Reset button in a form
onselect
script
onsubmit
script
Keyboard Events
Attribute onkeydown onkeypress onkeyup Value Description script script script Fires when a user is pressing a key Fires when a user presses a key Fires when a user releases a key
Mouse Events
Events triggered by a mouse, or similar user actions:
Attribute onclick ondblclick ondragNew ondragendNew ondragenterNew Value Description script script script script script Fires on a mouse click on the element Fires on a mouse double-click on the element Script to be run when an element is dragged Script to be run at the end of a drag operation Script to be run when an element has been dragged to a valid drop target Script to be run when an element leaves a valid drop target Script to be run when an element is being dragged over a valid drop target Script to be run at the start of a drag operation Script to be run when dragged element is being dropped Fires when a mouse button is pressed down on an element Fires when the mouse pointer moves over an element Fires when the mouse pointer moves out of an element Fires when the mouse pointer moves over an element
ondragleaveNew ondragoverNew
script script
Fires when a mouse button is released over an element Script to be run when the mouse wheel is being rotated Script to be run when an element's scrollbar is being scrolled
Media Events
Events triggered by medias like videos, images and audio (applies to all HTML elements, but is most common in media elements, like <audio>, <embed>, <img>, <object>, and <video>):
Attribute onabort oncanplayNew Value Description script script Script to be run on abort Script to be run when a file is ready to start playing (when it has buffered enough to begin) Script to be run when a file can be played all the way to the end without pausing for buffering Script to be run when the length of the media changes Script to be run when something bad happens and the file is suddenly unavailable (like unexpectedly disconnects)
oncanplaythroughNew
script
ondurationchangeNew onemptiedNew
script script
onendedNew
script
Script to be run when the media has reach the end (a useful event for messages like "thanks for listening") Script to be run when an error occurs when the file is being loaded Script to be run when media data is loaded Script to be run when meta data (like dimensions and duration) are loaded Script to be run just as the file begins to load before anything is actually loaded Script to be run when the media is paused either by the user o r programmatically Script to be run when the media is ready to start playing Script to be run when the media actually has started playing
onerrorNew
script
onloadeddataNew onloadedmetadataNew
script script
onloadstartNew
script
onpauseNew
script
onplayNew onplayingNew
script script
onprogressNew
script
Script to be run when the browser is in the process of getting the media data Script to be run each time the playback rate changes (like when a user switches to a slow motion or fast forward mode) Script to be run each time the ready state changes (the ready state tracks the state of the media data) Script to be run when the seeking attribute is set to false indicating that seeking has ended Script to be run when the seeking attribute is set to true indicating that seeking is active Script to be run when the browser is unable to fetch the media data for whatever reason Script to be run when fetching the media data is stopped before it is completely loaded for whatever reason Script to be run when the playing position has changed (like when the user fast forwards to a different point in the media) Script to be run each time the volume is changed which (includes setting the volume to "mute") Script to be run when the media has paused but is expected t o resume (like when the media pauses to buffer more data)
onratechangeNew
script
onreadystatechangeNew script
onseekedNew
script
onseekingNew
script
onstalledNew
script
onsuspendNew
script
ontimeupdateNew
script
onvolumechangeNew
script
onwaitingNew
script
Previous
Description
The HTML5 <canvas> tag is used to draw graphics, on the fly, via scripting (usually JavaScript). However, the <canvas> element has no drawing abilities of its own (it is only a container for graphics) - you must use a script to actually draw the graphics.
The getContext() method returns an object that provides methods and properties for drawing on the canvas. This reference will cover the properties and methods of the getContext("2d") object, which can be used to draw text, lines, boxes, circles, and more - on the canvas.
Browser Support
Internet Explorer 9, Firefox, Opera, Chrome, <canvas> and its properties and methods.
and
Safari
support
Note: Internet Explorer 8 and earlier versions, do not support the <canvas> element.
strokeStyle
shadowColor
shadowBlur
shadowOffsetX
Sets or returns the horizontal distance of the shadow from the shape
shadowOffsetY
Sets or returns the vertical distance of the shadow from the shape
Method createLinearGradient()
createPattern()
createRadialGradient()
addColorStop()
Line Styles
Property lineCap Description Sets or returns the style of the end caps for a line
lineJoin
Sets or returns the type of corner created, when two lines meet
lineWidth
miterLimit
Rectangles
Method rect() Description Creates a rectangle
fillRect()
strokeRect()
clearRect()
Paths
Method fill() Description Fills the current drawing (path)
stroke()
beginPath()
moveTo()
Moves the path to the specified point in the canvas, without creating a line
closePath()
Creates a path from the current point back to the starting point
lineTo()
Adds a new point and creates a line from that point to the last specified point in the canvas
clip()
Clips a region of any shape and size from the original canvas
quadraticCurveTo()
bezierCurveTo()
arc()
arcTo()
isPointInPath()
Returns true if the specified point is in the current path, otherwise false
Transformations
Method scale() Description Scales the current drawing bigger or smaller
rotate()
translate()
transform()
setTransform()
Resets the current transform to the identity matrix. Then runs transform()
Text
Property font Description Sets or returns the current font properties for text content
textAlign
textBaseline
Sets or returns the current text baseline used when drawing text
Method fillText()
strokeText()
measureText()
Image Drawing
Method drawImage() Description Draws an image, canvas, or video onto the canvas
Pixel Manipulation
Property width Description Returns the width of an ImageData object
height
data
Method
Description
createImageData()
getImageData()
Returns an ImageData object that copies the pixel data for the specified canvas
putImageData()
Puts the image data (from a specified ImageData object) back onto the canvas
Compositing
Property globalAlpha Description Sets or returns the current alpha or transparency value of the drawing
globalCompositeOperation
Sets or returns how a new image are drawn onto an existing image
Other
Method save() Description Saves the state of the current context
restore()
createEvent()
getContext()
toDataURL()
Description
The HTML5 <canvas> tag is used to draw graphics, on the fly, via scripting (usually JavaScript).
However, the <canvas> element has no drawing abilities of its own (it is only a container for graphics) - you must use a script to actually draw the graphics. The getContext() method returns an object that provides methods and properties for drawing on the canvas. This reference will cover the properties and methods of the getContext("2d") object, which can be used to draw text, lines, boxes, circles, and more - on the canvas.
Browser Support
Internet Explorer 9, Firefox, Opera, Chrome, <canvas> and its properties and methods.
and
Safari
support
Note: Internet Explorer 8 and earlier versions, do not support the <canvas> element.
strokeStyle
shadowColor
shadowBlur
shadowOffsetX
Sets or returns the horizontal distance of the shadow from the shape
shadowOffsetY
Sets or returns the vertical distance of the shadow from the shape
Method createLinearGradient()
createPattern()
createRadialGradient()
addColorStop()
Line Styles
Property lineCap Description Sets or returns the style of the end caps for a line
lineJoin
Sets or returns the type of corner created, when two lines meet
lineWidth
miterLimit
Rectangles
Method rect() Description Creates a rectangle
fillRect()
strokeRect()
clearRect()
Paths
Method Description
fill()
stroke()
beginPath()
moveTo()
Moves the path to the specified point in the canvas, without creating a line
closePath()
Creates a path from the current point back to the starting point
lineTo()
Adds a new point and creates a line from that point to the last specified point in the canvas
clip()
Clips a region of any shape and size from the original canvas
quadraticCurveTo()
bezierCurveTo()
arc()
arcTo()
isPointInPath()
Returns true if the specified point is in the current path, otherwise false
Transformations
Method scale() Description Scales the current drawing bigger or smaller
rotate()
translate()
transform()
setTransform()
Resets the current transform to the identity matrix. Then runs transform()
Text
Property font Description Sets or returns the current font properties for text content
textAlign
textBaseline
Sets or returns the current text baseline used when drawing text
Method fillText()
strokeText()
measureText()
Image Drawing
Method drawImage() Description Draws an image, canvas, or video onto the canvas
Pixel Manipulation
Property width Description Returns the width of an ImageData object
height
data
ImageData object
Method createImageData()
getImageData()
Returns an ImageData object that copies the pixel data for the specified rectangle on a canvas
putImageData()
Puts the image data (from a specified ImageData object) back onto the canvas
Compositing
Property globalAlpha Description Sets or returns the current alpha or transparency value of the drawing
globalCompositeOperation
Sets or returns how a new image are drawn onto an existing image
Other
Method save() Description Saves the state of the current context
restore()
createEvent()
getContext()
toDataURL()
buffered
controller
controls
Sets or returns the current playback position in the audio/video (in second Sets or returns if the audio/video is muted by default Sets or returns the default speed of the audio/video playback
Returns the length of the current audio/video (in seconds) Returns if the playback of the audio/video has ended or not Returns a MediaError object representing the error state of the audio/video Sets or returns if the audio/video should start over again when finished
loop
mediaGroup
Sets or returns a the group the audio/video belongs to (used to audio/video elements)
Sets or returns if the audio/video is muted or not Returns the current network state of the audio/video Sets or returns if the audio/video is paused or not Sets or returns the speed of the audio/video playback Returns a TimeRanges object representing the played parts of the audio/video Sets or returns if the audio/video should be loaded when the page loads Returns the current ready state of the audio/video
preload
Returns a TimeRanges object representing the seekable parts of the audio Returns if the user is currently seeking in the audio/video Sets or returns the current source of the audio/video element Returns a Date object representing the current time offset Returns a TextTrackList object representing the available text tracks Returns a VideoTrackList object representing the available video tracks Sets or returns the volume of the audio/video
canplaythrough durationchange emptied ended error loadeddata loadedmetadata loadstart pause play playing
Fires when the browser can play through the audio/video without stopping Fires when the duration of the audio/video is changed Fires when the current playlist is empty Fires when the current playlist is ended Fires when an error occurred during the loading of an audio/video Fires when the browser has loaded the current frame of the audio/video Fires when the browser has loaded meta data for the audio/video Fires when the browser starts looking for the audio/video Fires when the audio/video has been paused Fires when the audio/video has been started or is no longer paused Fires when the audio/video is ready to play after having been paused buffering Fires when the browser is downloading the audio/video Fires when the playing speed of the audio/video is changed
Fires when the user starts moving/skipping to a new position in the audio
Fires when the browser is trying to get media data, but data is not availab Fires when the browser is intentionally not getting media data Fires when the current playback position has changed Fires when the volume has been changed Fires when the video stops because it needs to buffer the next frame
To better handle today's internet use, HTML5 also includes new elements for better structure, better form handling, drawing, and for media content.
Isolates a part of text that might be formatted in a different direction from other text o Defines a command button that a user can invoke Defines additional details that the user can view or hide Defines a dialog box or window Defines a visible heading for a <details> element Specifies self-contained content, like illustrations, diagrams, photos, code listings, etc. Defines a caption for a <figure> element Defines a footer for a document or section Defines a header for a document or section Groups a set of <h1> to <h6> elements when a heading has multiple levels Defines marked/highlighted text Defines a scalar measurement within a known range (a gauge) Defines navigation links Represents 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 Defines a section in a document Defines a date/time
<wbr>
Removed Elements
The following HTML 4.01 elements are removed from HTML5: <acronym>
<applet> <basefont> <big> <center> <dir> <font> <frame> <frameset> <noframes> <strike> <tt>
HTML5 Canvas
Previous Next Chapter
The <canvas> element is used to draw graphics, on the fly, on a web page. Draw a red rectangle, a gradient rectangle, a multicolor rectangle, and some multicolor text onto the canvas:
What is Canvas?
The HTML5 <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript). The <canvas> element is only a container for graphics. You must use a script to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, characters, and adding images.
Browser Support
Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support the <canvas> element.
Note: Internet Explorer 8 and earlier versions, do not support the <canvas> element.
Create a Canvas
A canvas is a rectangular area on an HTML page, and it is specified with the <canvas> element. Note: By default, the <canvas> element has no border and no content. The markup looks like this:
Example
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"> </canvas>
Try it yourself
Example
<script> var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.fillStyle="#FF0000"; ctx.fillRect(0,0,150,75); </script>
var c=document.getElementById("myCanvas");
Then, call its getContext() method (you must pass the string "2d" to the getContext() method):
var ctx=c.getContext("2d");
The getContext("2d") object is a built-in HTML5 object, with many properties and methods for drawing paths, boxes, circles, text, images, and more. The next two lines draw a red rectangle:
ctx.fillStyle="#FF0000"; ctx.fillRect(0,0,150,75);
The fillStyle property can be a CSS color, a gradient, or a pattern. The default fillStyle is #000000 (black). The fillRect(x,y,width,height) method draws a rectangle filled with the current fill style.
Canvas Coordinates
The canvas is a two-dimensional grid. The upper-left corner of the canvas has coordinate (0,0) So, the fillRect() method above had the parameters (0,0,150,75). This means: Start at the upper-left corner (0,0) and draw a 150x75 pixels rectangle. Coordinates Example Mouse over the rectangle below to see its x and y coordinates: X Y
Canvas - Paths
To draw straight lines on a canvas, we will use the following two methods: moveTo(x,y) defines the starting point of the line lineTo(x,y) defines the ending point of the line
To actually draw the line, we must use one of the "ink" methods, like stroke().
Example
Define a starting point in position (0,0), and an ending point in position (200,100). Then use the stroke() method to actually draw the line: JavaScript:
Try it yourself To draw a circle on a canvas, we will use the following method: arc(x,y,r,start,stop)
To actually draw the circle, we must use one of the "ink" methods, like stroke() or fill().
Example
Create a circle with the arc() method: JavaScript:
Try it yourself
Canvas - Text
To draw text on a canvas, the most important property and methods are: font - defines the font properties for text fillText(text,x,y) - Draws "filled" text on the canvas strokeText(text,x,y) - Draws text on the canvas (no fill)
Using fillText():
Example
Write a 30px high filled text on the canvas, using the font "Arial": JavaScript:
Example
Write a 30px high text (no fill) on the canvas, using the font "Arial": JavaScript:
Try it yourself
Canvas - Gradients
Gradients can be used to fill rectangles, circles, lines, text, etc. Shapes on the canvas are not limited to solid colors.
There are two different types of gradients: createLinearGradient(x,y,x1,y1) - Creates a linear gradient createRadialGradient(x,y,r,x1,y1,r1) - Creates a radial/circular gradient
Once we have a gradient object, we must add two or more color stops. The addColorStop() method specifies the color stops, and its position along the gradient. Gradient positions can be anywhere between 0 to 1. To use the gradient, set the fillStyle or strokeStyle property to the gradient, and then draw the shape, like a rectangle, text, or a line. Using createLinearGradient():
Example
Create a linear gradient. Fill rectangle with the gradient: JavaScript:
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); // Create gradient var grd=ctx.createLinearGradient(0,0,200,0); grd.addColorStop(0,"red"); grd.addColorStop(1,"white"); // Fill with gradient ctx.fillStyle=grd; ctx.fillRect(10,10,150,80);
Example
Create a radial/circular gradient. Fill rectangle with the gradient: JavaScript:
Try it yourself
Canvas - Images
To draw an image on a canvas, we will use the following method: drawImage(image,x,y)
Image to use:
Example
Draw the image onto the canvas: JavaScript:
Try it yourself
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
can be searched, indexed, scripted, and compressed are scalable can be printed with high quality at any resolution are zoomable (and the image can be zoomed without degradation)
Browser Support
Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support inline SVG.
Example
<!DOCTYPE html> <html> <body> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="190"> <polygon points="100,10 40,180 190,60 10,60 160,180" style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;"> </svg> </body> </html>
Try it yourself Result: To learn more about SVG, please read our SVG Tutorial.
SVG is XML based, which means that every element is available within the SVG DOM. You can attach JavaScript event handlers for an element. In SVG, each drawn shape is remembered as an object. If attributes of an SVG object are changed, the browser can automatically re-render the shape. Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it is forgotten by the browser. If its position should be changed, the entire scene needs to be redrawn, including any objects that might have been covered by the graphic.
SVG
Browser Support
Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support drag and drop. Note: Drag and drop does not work in Safari 5.1.2.
Example
<!DOCTYPE HTML> <html>
<head> <script> function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("Text",ev.target.id); } function drop(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Text"); ev.target.appendChild(document.getElementById(data)); } </script> </head> <body> <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69"> </body> </html>
Try it yourself It might seem complicated, but lets go through all the different parts of a drag and drop event.
<img draggable="true">
event.preventDefault()
function drop(ev)
Canvas Resolution dependent No support for event handlers Poor text rendering capabilities You can save the resulting image as .png or .jpg Well suited for graphic-intensive games Resolution independent Support for event handlers Best suited for applications with large rendering areas (Google Maps) Slow rendering if complex (anything that uses the DOM a lot will be slow) Not suited for game applications
HTML5 Geolocation
Previous Next Chapter
Browser Support
Internet Explorer 9+, Firefox, Chrome, Safari and Opera support Geolocation. Note: Geolocation is much more accurate for devices with GPS, like iPhone.
Example
<script> var x=document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else{x.innerHTML="Geolocation is not supported by this browser.";} } function showPosition(position) { x.innerHTML="Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude; } </script>
Try it yourself Example explained: Check if Geolocation is supported If supported, run the getCurrentPosition() method. If not, display a message to the user If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter ( showPosition ) The showPosition() function gets the displays the Latitude and Longitude
The example above is a very basic Geolocation script, with no error handling.
Example
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; } }
Try it yourself 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
Example
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="<img src='"+img_url+"'>"; }
Try it yourself In the example above we use the returned latitude and longitude data to show the location in a Google map (using a static image). Google Map Script How to use a script to show an interactive map with a marker, zoom and drag options.
Location-specific Information
This page demonstrated how to show a user's position on a map. However, Geolocation is also very useful for location-specific information. Examples: Up-to-date local information Showing Points-of-interest near the user Turn-by-turn navigation (GPS)
The getCurrentPosition() method returns an object if it is successful. The latitude, longitude and accuracy properties are always returned. The other properties below are returned if available. Property coords.latitude Description The latitude as a decimal number
coords.longitude
coords.accuracy
coords.altitude
coords.heading
coords.speed
timestamp
Example
<script> var x=document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.watchPosition(showPosition);
} else{x.innerHTML="Geolocation is not supported by this browser.";} } function showPosition(position) { x.innerHTML="Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude; } </script>
Try it yourself
HTML5 Video
Previous Next Chapter
Many modern websites show videos. HTML5 provides a standard for showing them. Check if your browser supports HTML5 video
Check
Browser Support
Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support the <video> element. Note: Internet Explorer 8 and earlier versions, do not support the <video> element.
Example
<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>
Try it yourself The control attribute adds video controls, like play, pause, and volume. It is also a good idea to always include width and height attributes. If height and width are set, the space required for the video is reserved when the page is loaded. However, without these attributes, the browser does not know the size of the video, and cannot reserve the appropriate space to it. The effect will be that the page layout will change during loading (while the video loads). You should also insert text content between the <video> and </video> tags for browsers that do not support the <video> element. The <video> element allows multiple <source> elements. <source> elements can link to different video files. The browser will use the first recognized format.
MP4 YES
WebM NO
Ogg NO
Chrome 6+
YES
YES
YES
Firefox 3.6+
NO
YES
YES
Safari 5+
YES
NO
NO
Opera 10.6+
NO
YES
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
WebM
video/webm
Ogg
video/ogg
The example below illustrate, in a simple way, how to address a <video> element, read and set properties, and call methods.
Example 1
Create simple play/pause + resize controls for a video:
<source>
Defines multiple media resources for media elements, such as <video> and <aud
<track>
HTML5 Audio
Previous Next Chapter
Browser Support
Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support the <audio> element. Note: Internet Explorer 8 and earlier versions, do not support the <audio> element.
Try it yourself
The control attribute adds audio controls, like play, pause, and volume. You should also insert text content between the <audio> and </audio> tags for browsers that do not support the <audio> element. The <audio> element allows multiple <source> elements. <source> elements can link to different audio files. The browser will use the first recognized format.
Internet Explorer 9+
YES
NO
NO
Chrome 6+
YES
YES
YES
Firefox 3.6+
NO
YES
YES
Safari 5+
YES
YES
NO
Opera 10+
NO
YES
YES
Ogg
audio/ogg
Wav
audio/wav
<source>
Defines multiple media resources for media elements, such as <video> and <aud
Previous
Next Chapter
Note: Not all major browsers support all the new input types. However, you can already start using them; If they are not supported, they will behave as regular text fields.
Example
Select a color from a color picker:
Try it yourself
Example
Define a date control:
Try it yourself
Example
Define a date and time control (with time zone):
Try it yourself
Example
Define a date and time control (no time zone):
Try it yourself
Example
Define a field for an e-mail address (will be automatically validated when submitted):
Try it yourself Tip: Safari on iPhone recognizes the email type, and changes the on-screen keyboard to match it (adds @ and .com options).
Example
Define a month and year control (no time zone):
Try it yourself
Example
Define a numeric field (with restrictions):
Try it yourself Use the following attributes to specify restrictions: max - specifies the maximum value allowed min - specifies the minimum value allowed step - specifies the legal number intervals value - Specifies the default value
Example
Define a control for entering a number whose exact value is not important (like a slider control):
Try it yourself
Use the following attributes to specify restrictions: max - specifies the maximum value allowed min - specifies the minimum value allowed step - specifies the legal number intervals value - Specifies the default value
Example
Define a search field (like a site search, or Google search):
Try it yourself
Try it yourself
Example
Define a control for entering a time (no time zone):
Try it yourself
Example
Define a field for entering a URL:
Try it yourself Tip: Safari on iPhone recognizes the url input type, and changes the on-screen keyboard to match it (adds .com option).
Example
Define a week and year control (no time zone):
Try it yourself
Note: Not all major browsers support all the new input types. However, you can already start using them; If they are not supported, they will behave as regular text fields.
The color type is used for input fields that should contain a color.
Example
Select a color from a color picker:
Try it yourself
Example
Define a date control:
Try it yourself
Example
Define a date and time control (with time zone):
Try it yourself
Example
Define a date and time control (no time zone):
Try it yourself
Example
Define a field for an e-mail address (will be automatically validated when submitted):
Try it yourself Tip: Safari on iPhone recognizes the email type, and changes the on-screen keyboard to match it (adds @ and .com options).
The month type allows the user to select a month and year.
Example
Define a month and year control (no time zone):
Try it yourself
Example
Define a numeric field (with restrictions):
Try it yourself Use the following attributes to specify restrictions: max - specifies the maximum value allowed min - specifies the minimum value allowed step - specifies the legal number intervals value - Specifies the default value
The range type is used for input fields that should contain a value from a range of numbers. You can also set restrictions on what numbers are accepted.
Example
Define a control for entering a number whose exact value is not important (like a slider control):
Try it yourself Use the following attributes to specify restrictions: max - specifies the maximum value allowed min - specifies the minimum value allowed step - specifies the legal number intervals value - Specifies the default value
Example
Define a search field (like a site search, or Google search):
Try it yourself
Try it yourself
Example
Define a control for entering a time (no time zone):
Try it yourself
Example
Define a field for entering a URL:
Try it yourself Tip: Safari on iPhone recognizes the url input type, and changes the on-screen keyboard to match it (adds .com option).
Example
Define a week and year control (no time zone):
Try it yourself
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.
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
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
Example
Perform a calculation and show the result in an <output> element:
<form oninput="x.value=parseInt(a.value)+parseInt(b.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
<keygen>
<output>
New attributes for <input>: autocomplete autofocus form formaction formenctype formmethod formnovalidate formtarget height and width list min and max multiple pattern (regexp) placeholder required step
Note: The autocomplete attribute works with <form> and the following <input> types: text, search, url, tel, email, password, datepickers, range, and color.
Example
An HTML form with autocomplete on (and off for one input field):
<form action="demo_form.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.
Example
Indicates that the form is not to be validated on submit:
<form action="demo_form.asp" novalidate> E-mail: <input type="email" name="user_email"> <input type="submit"> </form>
Try it yourself
Example
Let the "First name" input field automatically get focus when the page loads:
Try it yourself
Example
An input field located outside the HTML form (but still a part of the form):
<form action="demo_form.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
Example
An HTML form with two submit buttons, with different actions:
<form action="demo_form.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.asp" value="Submit as admin"> </form>
Try it yourself
Example
Send form-data that is default encoded (the first submit button), and encoded as "multipart/form-data" (the second submit button):
<form action="demo_post_enctype.asp" method="post"> First name: <input type="text" name="fname"><br> <input type="submit" value="Submit">
Try it yourself
Example
The second submit button overrides the HTTP method of the form:
<form action="demo_form.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.asp" value="Submit using POST"> </form>
Try it yourself
Example
A form with two submit buttons (with and without validation):
<form action="demo_form.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
Example
A form with two submit buttons, with different target windows:
<form action="demo_form.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
Example
Define an image as the submit button, with height and width attributes:
Try it yourself
Example
An <input> element with pre-defined values in a <datalist>:
<input list="browsers"> <datalist <option <option <option <option id="browsers"> value="Internet Explorer"> value="Firefox"> value="Chrome"> value="Opera">
Try it yourself
Example
<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
Example
A file upload field that accepts multiple values:
Try it yourself
Example
An input field that can contain only three letters (no numbers or special characters):
Country code: <input type="text" name="country_code" pattern="[A-Zaz]{3}" title="Three letter country code">
Try it yourself
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.
Example
An input field with a placeholder text:
Try it yourself
Example
A required input field:
Try it yourself
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.
Example
An input field with a specified legal number intervals:
Try it yourself
<input>
Browser Support
Web storage is supported in Internet Explorer 8+, Firefox, Opera, Chrome, and Safari. Note: Internet Explorer 7 and earlier versions, do not support web storage.
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.. }
Example
localStorage.lastname="Smith"; document.getElementById("result").innerHTML="Last name: " + localStorage.lastname;
Try it yourself Example explained: Create a localStorage key/value pair with key="lastname" and value="Smith" Retrieve the value of the "lastname" key and insert it into the element with id="result"
Tip: Key/value pairs are always stored as strings. Remember to convert them to another format when needed. The following 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:
Example
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).";
Try it yourself
The 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. The following example counts the number of times a user has clicked a button, in the current session:
Example
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.";
Try it yourself
With HTML5 it is easy to make an offline version of a web application, by creating a cache manifest file.
Application cache gives an application three advantages: 1. Offline browsing - users can use the application when they're offline 2. Speed - cached resources load faster 3. Reduced server load - the browser will only download updated/changed resources from the server
Browser Support
Internet Explorer 10, Firefox, Chrome, Safari and Opera support Application cache.
Example
<!DOCTYPE HTML> <html manifest="demo.appcache"> <body> The content of the document...... </body> </html>
Try it yourself
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/cachemanifest". Must be configured on the web server.
CACHE MANIFEST
The first line, CACHE MANIFEST, is required:
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 /html/ catalog, in case an internet connection cannot be established:
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).
A web worker is a JavaScript running in the background, without affecting the performance of the page.
Browser Support
Internet Explorer 10, Firefox, Chrome, Safari and Opera support Web workers.
Example
Count numbers: Start Worker Stop Worker
Try it yourself
if(typeof(Worker)!=="undefined") { // Yes! Web worker support! // Some code..... } else { // Sorry! No Web Worker support.. }
w.onmessage=function(event){ document.getElementById("result").innerHTML=event.data; };
When the web worker posts a message, the code within the event listener is executed. The data from the web worker is stored in event.data.
w.terminate();
Example
<!DOCTYPE html> <html> <body>
<p>Count numbers: <output id="result"></output></p> <button onclick="startWorker()">Start Worker</button> <button onclick="stopWorker()">Stop Worker</button> <br><br> <script> var w; function startWorker() { if(typeof(Worker)!=="undefined") { if(typeof(w)=="undefined") { w=new Worker("demo_workers.js"); } w.onmessage = function (event) { document.getElementById("result").innerHTML=event.data; }; } else { document.getElementById("result").innerHTML="Sorry, your browser does not support Web Workers..."; } } function stopWorker() { w.terminate(); } </script> </body> </html>
Try it yourself
HTML5 Server-Sent Events allow a web page to get updates from a server.
Browser Support
Server-Sent Events are supported in all major browsers, except Internet Explorer.
Example
var source=new EventSource("demo_sse.php"); source.onmessage=function(event) { document.getElementById("result").innerHTML+=event.data + "<br>"; };
Try it yourself Example explained: Create a new EventSource object, and specify the URL of the page sending the updates (in this example "demo_sse.php") Each time an update is received, the onmessage event occurs When an onmessage event occurs, put the received data into the element with id="result"
if(typeof(EventSource)!=="undefined") { // Yes! Server-sent events support! // Some code..... } else { // Sorry! No server-sent events support.. }
<?php header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); $time = date('r'); echo "data: The server time is: {$time}\n\n";
flush(); ?>
Code in ASP (VB) (demo_sse.asp):
onmessage
onerror
HTML Multimedia
Previous
Next Chapter
Multimedia on the web is sound, music, videos, and animations. Modern web browsers have support for many multimedia formats.
What is Multimedia?
Multimedia comes in many different formats. It can be almost anything you can hear or see. Examples: Pictures, music, sound, videos, records, films, animations, and more. Modern Web pages have often embedded multimedia elements, and modern browsers have support for various multimedia formats. In this tutorial you will learn about different multimedia formats.
Browser Support
The first Internet browsers had support for text only, and even the text support was limited to a single font in a single color. Then came browsers with support for colors, fonts and text styles, and support for pictures was added. The support for sounds, animations, and videos is handled in different ways by various browsers. Some multimedia elements is supported, and some requires an extra helper program (a plug-in). You will learn more about plug-ins in the next chapters.
Multimedia Formats
Multimedia elements (like sounds or videos) are stored in media files. The most common way to discover the type of a file, is to look at the file extension. When a browser sees the file extension .htm or .html, it will treat the file as an HTML file. The .xml extension indicates an XML file, and the .css extension indicates a style sheet file. Pictures are recognized by extensions like .gif, .png and .jpg. Multimedia files also have their own formats with different extensions like: .swf, .wav, .mp3, and .mp4.
Video Formats
MP4 is the new and upcoming format for internet video. It is supported by YouTube, Flash players and HTML5.
Format AVI
File .avi
Description
AVI (Audio Video Interleave) was developed by Microsoft. AVI is supported by all co running Windows, and by the most popular web browsers. It is a very common form Internet, but not always possible to play on non-Windows computers
WMV
.wmv
WMV (Windows Media Video) was developed by Microsoft. WMV is a common forma Internet, but it cannot be played on non-Windows computer without an extra (free) installed. Some later WMVs cannot play at all on non-Windows computers because n available
MPEG
.mpg The MPEG (Moving Pictures Expert Group) format is the most popular format on the .mpeg cross-platform, and supported by all major browsers
QuickTime .mov
QuickTime was developed by Apple. QuickTime is a common format on the Internet QuickTime movies cannot be played on a Windows computer without an extra (free installed.
RealVideo
.rm .ram
RealVideo was developed by Real Media. RealVideo allows streaming of video (onlin Internet TV) with low bandwidths. Because of the low bandwidth priority, the qualit reduced
Flash
.swf .flv
Flash was developed by Macromedia. Flash requires an extra component to play. Th comes preinstalled with all major browsers
MP4
.mp4
Mpeg-4 (MP4) is the new format for the internet. YouTube recommends using MP4. accepts multiple formats, and then converts them all to .flv or .mp4 for distribution
Sound Formats
MP3 is the newest format for compressed recorded music. The term MP3 has become synonymous with digital music. If your website is about recorded music, the MP3 format is the choice.
Format MIDI
Description
MIDI (Musical Instrument Digital Interface) is a format for electronic music devices li synthesizers and PC sound cards. MIDI files do not contain sound, but digital musical (notes) that can be played by electronics (like your PC's sound card). Click here to play The Beatles.
Since MIDI files only contains instructions; they are extremely small. The example ab 23K in size, but it plays for nearly 5 minutes. MIDI is supported by many software systems/platforms. MIDI is supported by all the most popular Internet browsers.
MP3
.mp3 MP3 files are actually the sound part of MPEG files. MPEG was originally developed fo Moving Pictures Experts Group. MP3 is the most popular format for music. The encod combines good compression (small files) with high quality
RealAudio was developed Real Media. It allows streaming of audio (online music, Inte with low bandwidths. Because of the low bandwidth priority, the quality is often redu
WAV
.wav
WAVE (more known as WAV) was developed by IBM and Microsoft. WAVs are compat Windows, Macintosh, and Linux operating systems
WMA
.wma WMA (Windows Media Audio), compares in quality to MP3, and is compatible with mo except the iPod. WMA files can be delivered as a continuous flow of data, which make for use in Internet radio or on-line music.
Plug-ins can be added to Web pages through the <object> tag or the <embed> tag. Most plug-ins allow manual (or programmed) control over settings for volume, rewind, forward, pause, stop, and play.
Try it yourself
Try it yourself
Try it yourself
Example
<object width="100%" height="100%" type="video/x-ms-asf" url="3d.wmv" data="3d.wmv" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"> <param name="url" value="3d.wmv"> <param name="filename" value="3d.wmv"> <param name="autostart" value="1"> <param name="uiMode" value="full"> <param name="autosize" value="1"> <param name="playcount" value="1"> <embed type="application/x-mplayer2" src="3d.wmv" width="100%" height="100%" autostart="true" showcontrols="true" pluginspage="http://www.microsoft.com/Windows/MediaPlayer/"></embed> </object>
Try it yourself
Plug-ins
Plug-ins can be used for many purposes: to display maps, scan for viruses, verify your bank id, and much more. The restrictions are few.
HTML Audio
Previous Next Chapter
Using Plug-ins
A plug-in is a small computer program that extends the standard functionality of the browser. Plug-ins can be added to HTML pages using the <object> tag or the <embed> tag. These tags define containers for resources (normally non-HTML resources), which, depending on the type, will either be displayed by the browsers, or by an external plugin.
Example
<embed height="50" width="100" src="horse.mp3">
Try it yourself
Problems:
Different browsers support different audio formats If a browser does not support the file format, the audio will not play without a plug-in If the plug-in is not installed on the users' computer, the audio will not play If you convert the file to another format, it will still not play in all browsers
Example
<object height="50" width="100" data="horse.mp3"></object>
Try it yourself
Problems:
Different browsers support different audio formats If a browser does not support the file format, the audio will not play without a plug-in If the plug-in is not installed on the users' computer, the audio will not play If you convert the file to another format, it will still not play in all browsers
Example
<audio controls> <source src="horse.mp3" type="audio/mpeg"> <source src="horse.ogg" type="audio/ogg"> Your browser does not support this audio format. </audio>
Try it yourself
Problems:
You must convert the audio files into different formats The <audio> element does not work in older browsers
Example
<audio controls height="100" width="100"> <source src="horse.mp3" type="audio/mpeg"> <source src="horse.ogg" type="audio/ogg"> <embed height="50" width="100" src="horse.mp3"> </audio>
Try it yourself
Problems:
You must convert the audio files into different formats The <embed> element cannot "fall-back" to display an error message
Example
<a href="horse.mp3">Play Sound</a> <script src="http://mediaplayer.yahoo.com/js"></script>
Try it yourself To use it, insert the following JavaScript at the bottom of your web page:
<script src="http://mediaplayer.yahoo.com/js"></script>
Then, simply link to your audio files in your HTML, and the JavaScript code automatically creates a play button for each song: <a href="song1.mp3">Play Song 1</a> <a href="song2.wav">Play Song 2</a> ... ... The Yahoo Media Player presents your readers with a small play button instead of a full player. However, when you click the button, a full player pops up. Note that the player is always docked and ready at the bottom of the window. Just click on it to slide it out.
Using A Hyperlink
If a web page includes a hyperlink to a media file, most browsers will use a "helper application" to play the file. The following code fragment displays a link to an MP3 file. If a user clicks on the link, the browser will launch a helper application to play the file:
Example
<a href="horse.mp3">Play the sound</a>
Try it yourself
If you plan to use inline sounds, be aware that many people will find it annoying. Also note that some users might have turned off the inline sound option in their browser. Our best advice is to include inline sounds only in pages where the user expects to hear sounds. An example of this is a page which opens after the user has clicked on a link to hear a recording.
<object>
<param>
<audio>New
<video>New
<source>New
Defines multiple media resources for media elements (<video> and <audio>)
<track>New
HTML Videos
Previous Next Chapter
Try it yourself
Example
<embed src="intro.swf" height="200" width="200">
If the browser does not support Flash, the video will not play iPad and iPhone do not support Flash videos If you convert the video to another format, it will still not play in all browsers
Example
<object data="intro.swf" height="200" width="200"></object>
Try it yourself Problems: If the browser does not support Flash, the video will not play iPad and iPhone do not support Flash videos If you convert the video to another format, it will still not play in all browsers
Example
<video width="320" height="240" controls> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> <source src="movie.webm" type="video/webm"> Your browser does not support the video tag. </video>
Try it yourself Problems: You must convert your videos to many different formats
Try it yourself Problems: You must convert your videos to many different formats
Using A Hyperlink
If a web page includes a hyperlink to a media file, most browsers will use a "helper application" to play the file. The following code fragment displays a link to a Flash video. If a user clicks on the link, the browser will launch a helper application to play the file:
Example
<a href="intro.swf">Play a video file</a>
Try it yourself
<object>
<param>
<audio>New
<video>New
<source>New
Defines multiple media resources for media elements (<video> and <audio>)
<track>New
Pr