New HTML5 features

Source: Internet
Author: User
Tags valid email address sessionstorage
1. Canvas 1.1 rectangle and Line Drawing

The fillstyle and strokestyle attributes allow you to easily set the filling and line of a rectangle. The color value is used in the same way as CSS: hexadecimal number, RGB (), rgba (), and HSLA. You can use fillrect to draw a rectangle with padding. You can use strokerect to draw a rectangle that is not filled with a border. If you want to clear some of the canvas, you can use clearrect. The parameters of the preceding three methods are the same: X, Y, width, and height. The first two parameters set the coordinates (x, y), and the last two parameters set the height and width of the rectangle. You can use the linewidth attribute to change the line width.

context.fillStyle = ‘#00f’;//bluecontext.strokeSyle = ‘#f00’;//redcontext.lineWidth = 4;//draw some rectanglescontext.fillRect(0,0,150,50);context.strokeRect(0,60,150,50);context.clearRect(30,25,90,60);context.strokeRect(30,25,90,60);

Path:

// Draw the triangle context. fillstyle = '# 00f'; // bluecontext. strokesyle = '# f00'; // redcontext. linewidth = 4; context. beginpath (); // start to draw context. moveTo (10, 10); // (x, y) Coordinate context. lineto (100,10); context. lineto (10,100); context. lineto (10, 10); context. fill (); context. stroke (); context. closepath (); // end the painting
1.2 Insert an image

The drawimage method allows you to insert other images into the canvas. (IMG and Canvas elements ). In opera, you can draw SVG images in canvas. This method can have 3, 5, or 9 parameters.

Three parameters: the most basic drawimage usage method. One parameter specifies the image position, and the other two parameters set the position of the image in the canvas.

Context. drawimage (img_elem, dx, Dy );

Five parameters: Intermediate drawimage usage, including the three parameters described above, add two parameters to specify the width and height of the inserted image (change the image size ).

Context. drawimage (img_elem, dx, Dy, DW, DH );

Nine parameters: the most complex drawimage usage method, including the preceding five parameters. The other four parameters are used to set the position and height width of the source image. These parameters allow you to dynamically crop the source image before displaying the image.

Context. drawimage (img_elem, Sx, Sy, SW, sh, dx, Dy, DW, DH );

1.3 pixel operation

The 2D context API provides three methods for Pixel-level operations: createimagedata, getimagedata, and putimagedata. The imagedata object stores the image pixel value. Each object has three attributes: width, height, and data. The data attribute type is canvaspixelarray, which is used to store width * height * 4 pixel values. Each pixel has an RGB value and a transparency Alpha value (its value ranges from 0 to 255, including alpha !). The pixel sequence is stored from left to right, from top to bottom, by row.

· Draw a red rectangle
VaR imgd = context. creatimagedata (50, 50 );
VaR pix = imgd. Data;
For(VAR I = 0; n <pix. length, I <n; I + = 4 ){
PIX [I] = 255;
PIX [I + 3] = 127;
}
Context. putimagedata (imgd, 0, 0 );

· Color Reversal Filter
VaR imgd = context. getimagedata (X, Y, width, height );
VaR pix = imgd. Data;
For(VAR I = 0, n = pix. length; I <n; I + = 4 ){
PIX [I] = 255-pix [I];
PIX [I + 1] = 255-pix [I + 1];
PIX [I + 2] = 255-pix [I + 2];
}
Context. putimagedate (imgd, x, y );

1.4 text writing

You can set the following text attributes for the context object:

Font: text font, similar to the font-Family of CSS;

Textalign: horizontal alignment of text. Optional property values: Start, end, left, right, and center. Default Value: Start.

Textbaseline: vertical alignment of text. Optional attribute values: Top, hanging, middle, alphabetic, ideographic, and bottom. Default Value: Alphabetic

· There are two ways to draw text:

Filltext: Draw text filled with fillstyle.

Stroketext: Draw text with only the strokestyle border. The two parameters are the same:

Coordinates of the text and text to be drawn (x, y. There is also an optional option-maximum width.

· Shadow effect:

Not supported by Chrome, but supported by Firefox.

The properties of shadows API are as follows:

Shadowcolor: Specifies the shadow color. The value is consistent with the CSS color value.

Shadowblur: sets the shadowblur blur level. The larger the value, the blurrier the shadow. The effect is the same as that of the Gaussian blur filter in Photoshop.

Shadowoffsetx and shadowoffsety: the offset between x and y of the shadow, in pixels.

Example:

context.shadowOffsetX=5;context.shadowOffsetY=5;context.shadowBlur=4;context.shadowColor=‘rgba(255,0,0,0.5)’;context.fillStyle=‘#00f’;context.fillRect(20,20,150,100);
1.5 color gradient

 

In addition to the CSS color, the fillstyle and strokestyle attributes can be set as canvasgradient objects. -- Use canvasgradient to change the color gradient for lines and fills. To create a canvasgradient object, you can use the createlineargradient and createradialgradient methods. The former creates a linear color gradient, and the latter creates a circular color gradient. After creating a color gradient object, you can use the addcolorstop method of the object to add the color median.

VaR gradient1 = context. creatlineargradient (sx, Sy, dx, Dy); // the start point and end point are changed from 0 to 1gradient1. addcolorstop (0, '# f00'); // redgradient1.addcolorstop (0.5,' # ff0'); // yellowgradient1.addcolorstop (1, '# 00f '); // blue \ // create a circular gradient that refers to the center of the circle, including the start and end, and the radius of the circle var gradient2 = context. creatradialgradient (sx, Sy, Sr, dx, Dy, Dr); // Add colors and linearity
2. Form2.1 type = Number

The HTML form element of type = number can be used to change the value in the text box by pressing a key.

Number of students:

<input type=”number” value=”1”/>
2.2 type = range

Type = range indicates the range of regions where a value can be selected.

<input type=”range” value=”50”/>
2.3 type = data and other time controls

Type = data indicates the time selector control.

Select Date:

<input type=”data”value=”2011-11-14”>
2.4 type = color

Type = color indicates the color selector control.

Select color:

<input type=”color”value=”#34538b”>
2.5 type = search

 

Type = search indicates the search function.

2.6datalist element and list attribute

Datalist is used to pull down the data list.

<Input type = "text" list = "mydata" Placeholder = "top movies"/> <datalist id = "mydata"> <option label = "top1" value = "Let the bullet fly "> <option label =" top2 "value =" if you are the only one "> <option label =" top3 "value =" "> <option label =" top4 "value =" orphan Zhao "> <option label =" top5 "value =" First Love "> </datalist>
3. Video and audio 3.1 video

Ogg is a file with theora video encoding and Vorbis Audio Encoding;

MPEG4 is an MPEG4 file with H.264 video encoding and AAC audio encoding;

Webm is a Vp8 video encoding and Vorbis Audio Encoding file;

The HTML5 specification does not specify a specific video decoder, which is left to the browser.

Safari and ie9 are expected to support videos in H.264 format. Firefox and opera adhere to the open-source theora and Vorbis formats. Therefore, two formats are required.

Video supports three video formats: Ogg, MPEG4, and webm.

Example:

<Video controls = "preload">

// This attribute indicates that the video is loaded during page loading and is ready to be played. If it is set to autoplay, this attribute is ignored.

// Controls used to display playback buttons

<Source src = "cohagenphonecall. OGV" type = "Video/Ogg; codecs = 'vorbis, theora '"/>

<Source src00000000cohagenphonecall.mp4"

Type = "vide0/MP4; codecs = 'avc1. 42e01e, mp4a. 100'"/>

<P> your browser is too old. <A href000000000000cohagenphonecall.mp4 "> download this video. </A> </P>

</Video>

Note:

· Technically, you do not need to set the type attribute. If you do not do this, the browser will search for the type by itself. To save some bandwidth, it is best to declare it.

· Not all browsers support HTML5. Therefore, you can provide a download link or an embedded video flash version under the resource element, depending on the individual.

· If you want all browsers to support HTML5 tags, you only need to link a JS file. Write the following in the header or bottom of the page:
<SCRIPT src = "http://html5media.googlecode.com/svn/trunk/src/html5media.min.js”>
</SCRIPT>

For the HTML section, use:

<Video src00000000video.mp4 "width =" 320 "Height =" 240 "controls =" autobuffer ">

</Video>

3.2 audio

You no longer need to rely on the third-party Production Check area to render the audio, because HTML5 provides the <audio> element.

The firefoxbrowser with the moozillacore only supports .ogg files. The webkitcore browser supports .mp3expansion, and safaridoes not support .ogg. It skips and moves to the MP3 version. Therefore, you must create two versions of audio.

Audio supports three audio formats: Ogg Vorbis, MP3, and WAV.

Example:

<Audio autoplay = "autoplay" controls = "controls">

<Source src00000000file.ogg "/>

<Source src?#file="/>

</Audio>

// The tag attributes are the same as those of video. No height or width.

4. Web Storage4.1 localstorage

Localstorage can store data for a long time without time restrictions.

4.2 sessionstorage

Sessionstorage cannot store data for a long time, and the data will be deleted as the browser closes.

5. HTML5 features

 

5.1.1 new doctype

 

<! Doctype HTML>

5.1.2 graphic elements

 

<P> image of Mars </P>

Text is wrapped in P labels, and IMG labels are different. It is hard to think of this as the title. HTML5 uses the figure element for correction. When used in combination with figcaption, the title corresponding to the image can be syntactically recognized.

<Figure>

<Figcaption>

<P> This is an image of somethinginteresting </P>

</Figcaption>

</Figure>

5.1.3 <small> redefinition

<Small> elements are no longer used to create subtitles that are near the logo. In HTML5, <small> is redefined, indicating a small character.

5.1.4 script (scripts) and link (LINKS) do not require type

<LINK rel = "stylesheet" href = "path/to/stylesheet.css" type = "text/CSS"/>

<SCRIPT type = "text/JavaScript" src = "path/to/script. js"> </SCRIPT>

In HTML5:

<LINK rel = "stylesheet" href = "path/to/stylesheet.css">

<SCRIPT src = "path/to/script. js"> </SCRIPT>

5.1.5 quotation marks

HTML5 is not XHTML, so quotation marks are not required.

<PClass= "Myclass" id = someid> startthe Reactor

However, if the structure is preferred, quotation marks must be added.

5.1.6 content editable

As the name suggests, the contenteditable element allows users to edit any text contained in the element content.

<ul contenteditable=”true”><li>hello</li><li>Beijing</li><li>trs</li></ul>
5.1.7email input (input)

In the form input box, apply the type attribute "email". You can command the browser to only allow strings that match the valid email address structure. But older browsers do not recognize them, and they are simply returned to common text boxes.

<Form action = "" method = "get"> <label for = "email"> Email: </label> <input id = "email" name = "email" type = "email"/> <button type = "Submit"> OK </button> </form>
5.1.8 placeholder (placeholders)

Placeholders indicates that a text prompt is displayed by default in the text box/Text domain space. when the focus is obtained, the text will disappear. If the focus is lost, the text will appear again. The prompt text displayed in the form control is a placeholder.

If some JavaScript code is used to implement placeholder operations, HTML5 makes it very easy:

<LabelFor= "Email"> Email: </label>

<Input id = "email" type = "email" Placeholder = "trs@trs.com" size = "26"/>

Generally, WebKit core browsers support this feature, such as chrome and safari.

5.1.9 Local Storage)

Traditional HTML uses well-known cookies, which are supported by various browsers and can be called directly using JS, which is very convenient. However, traditional cookies also have their own shortcomings. For example, if the storage space is small, the size of each site is limited to around 4 kb and there is a time limit, and the cookie will be included in the header of each HTTP request when requesting the webpage, therefore, the traffic is virtually increased. In HTTP requests, cookies are transmitted in plain text, so security issues exist. SSL (Secure Sockets Layer) is used as a security protocol for network communication) channels are also a different theory. Cookies are also vulnerable to cross-site attacks. Add "? Cookie = Document. Cookie "can easily obtain the user's cookie information. HTML5 local storage may also have cross-site scripting (XSS) Attacks
Site Script, cross-site scripting attacks. A malicious attacker inserts malicious HTML code into the web. When a user browses this page, the HTML code embedded in the Web is executed .) .

HTML5 local storage can store 5 MB of data, or even more. It mainly has four types: localstorage, sessionstorage, websql, indexdb

Example:

<ul id="edit" contenteditable="true"><li><li></ul><script language="javascript"><!--var edit=document.getElementById(edit);edit.onblur=function(){localStorage.setItem("tododata",this.innerHtml);};if(localStorage.getItem("tododata")){Edit.innerHTML = localStorage.getItem("tododata");}//--></script>

5.2.0 semantic headers and footer

Past:

<Div id = "Header">

...

</Div>

<Div id = "footer">

...

</Div>

With HTML5, you can directly replace it;

<Header>

...

</Header.

<Footer>

...

</Footer>

5.2.1ie and HTML5

All elements have a default inline display. To ensure that all new elements are correctly rendered using blocks, you need to define them as follows:

Header, footer, article, section, NAV, menu, hgroup {

Display: block;

}

However, because IE does not recognize some labels, such as headers, these styles are ignored, you need to create elements:

Document. createlement ("artical ");

Document. createlement ("footer ");

Document. createlement ("Header ");

Document. createlement ("nav ");

Document. createlement ("menu ");

Document. createlement ("hgroup ");

Another solution:

<! -[IfIE]>

<SCRIPT src = "http://html5shim.googlecode.com/svn/trunk/html5.js”> </SCRIPT>

<! [Endif] -->

5.2.2 information about a part of the document (hgroup)

The hgroup element can be used to combine titles.

<Header>

<Hgroup>

<H1> recall fan page

<H2> onlyForPeople whowant the memory of a lifetime. </H2>

</Hgroup>

</Header>

5.2.3 required attributes (required attribute)

<Input type = "text" name = "someinput" required>

Or use a more structured method:

<Input type = "text" name = "someinput" required = "required">

If the "someinput" text box is blank, the form will not be submitted.

<Form action = "method =" get ">

<LableFor= "Name"> name: </label>

<Input id = "name" name = "name" type = "text" Placeholder = "TRS" required = "required"/>

<Button type = "Submit"> submit <button>

</Form>

If the content in the input is blank, the text box is highlighted when the form is submitted, but it seems that this effect is only available in chrome.

5.2.4autocomplete attributes

The AutoComplete attribute specifies that the form or input field should have the function of Automatic completion.

It is used for the <form> label and the following <input> labels: Text, search, URL, telephone, email, password, datapickers, range, and color.

<Form action = "method =" get "AutoComplete =" on ">

<LabelFor= "Email"> Email: </label>

<Input type = "email" name = "email" AutoComplete = "off"/>

</Form>

5.2.5 Regular Expression

Regular Expressions can be used to easily verify a specific text.

<Form action = "method =" get ">

<LabelFor= "Username"> name: </label>

<Input id = "username" name = "username" type = "text" Placeholder = "4-10 letters"

Pattern = "[A-Za-Z] {4, 10}" required = "required" autofocus/>

<Button type = "Submit"> submit </button>

</Form>

In [A-Za-Z] {}, it indicates that 4-10 letters are accepted, which are case-insensitive. This feature seems to be only supported in chrome.

5.2.6 attributes support Detection

Leverage the excellent modernizr Library (http://www.modernizr.com/)Check whether the browser supports certain attributes.

You only need to create and analyze these elements to determine the capabilities of the browser. In fact, this is a common method to determine browser compatibility. For example, to determine the pattern attribute, add a small piece of code in the pattern Crip:

Alert ('pattern' in document. createlement ('input'); // Boolean

// Creates a new input element and determines whether the pattern attribute browser supports it.

You can also:

<SCRIPT>

If (! 'Pattern' in document. createlement ('input ')){

// Perform the operation

}

</SCRIPT>

 

5.2.7mark Element)

<Mark> the element is highlighted. The string of this label package should be associated with the user's current action.

5.2.8div

Div should be used when there are no better elements. For example, you need to enclose a block of code in the packaging unit for content locating. However, for an article, you 'd better use <artical>. For a link list, use <nav>.

5.2.9 minor knowledge

· SVG (Scalable Vector Graphics) is not HTML5. It is based on Extensible Markup Language (XML) and is used to describe two-dimensional vector graphs.

· Geolocation is not HTML5, which means the geographical location. Through HTML5, web applications can determine the location and provide more information.

· Retrieve the value of custom attributes:

5.3.0data attributes

HTML code: <Div id = "mydiv" data-custom-ATTR = "my value"> Lady Ga </div>

Search:

VaR thediv = Document. getelementbyid ("mydiv ");

VaR ATTR = thediv. getattribute ("data-custom-ATTR ");

Alert (ATTR); // my value

· Application of this attribute in CSS

CSS code:

. Data_custom {display: inline-block; position: relative ;}

. Data_custom: hover {color: ransparent ;}

. Data_custom: hover: After {

Content: ATTR (data-hover-response );

Color: black;

Position: absolute;

Left: 0;

}

HTML code:

<Class= "Data_custom" data-hover-response = "I said don't touch me !" Href = "#"> don't touch me, grack </a>

Note: The browser supports the ATTR of the pseudo-class after-season content.

5.3.1 Use regional input to create a slider

HTML5 introduces the range type input.

<Input type = "range">, which can receive attributes such as Min, Max, step, and value.

· Tag
<Form method = "Post">
<H4> volume control </H4>
<Input type = "range" name = "range" min = "0" max = "10" step = "1" value = ""/>
<Output name = "result"> </output>
</Form>

· CSS

Use before and after to notify the user of the specified maximum and minimum values.

Input {font-size: 14px; font-weight: bold ;}

Input [type = range]: Before {content: ATTR (min): padding-Right: 5px ;}

Input [type = range]: After {content: ATTR (max): padding-left: 5px}

Output {

Display: block;

Font-size: 5.5em;

Font-weight: bold;

}

· Javascript

L checks whether the browser can recognize rangeinput. If not, a prompt is displayed;

L when the user moves the slider, the output value is dynamically changed;

L listener. When the user leaves the slider, the value is inserted and stored locally;

L when the page is refreshed, the selected region and value are automatically set to the last selection.

(Function (){

VaR F = Document. Forms [0], // return reference to all documents in the object

Range = f ['range'],

Result = f ['result'],

Cachedrangevalue = localstorage. rangevalue? Localstorage. rangevalue: 5;

// Check whether the browser is cool.

// Recognize Range Input

VaR o = Document. createlement ('input ');

O. type = 'range ';

If(O. type = 'text ')

Alert ('Sorry, your browser is not cool enough. Please try the latest Chrome browser! ');

// Set the Initial Value

// Set the value to 5 regardless of local storage.

Range. value = cachedrangevalue;

Result. value = cachedrangevalue;

// When you select a value to update the local storage

Range. addeventlistener ("mouseup", function (){

Alert ("your choice is:" + range. Value + "I am currently using local storage to save this value. Refresh the verification in the browser .");

Localstorage? (Localstorage. rangevalue = range. Value): Alert ("data is saved to the database or somewhere else .");

},False);

// Slide to display the selected value

Range. addeventlistner ("change", function (){

Result. value = range. value;

},False);

})();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.