Many friends have privately messaged me and asked me about the new features and usage of html5. Let me give you a detailed introduction to the new features of html5. Let me summarize them for you.
1) New semantic tags footer header, etc. 2) Enhanced Forms 2.0 3) Audio and video 4) Canvas drawing 5) SVG drawing 6) Geolocation 7) Drag and drop API 8) Web worker to perform time-consuming tasks 9 ) web Storage stores large amounts of data on the browser side 10) web Socket is a persistent connection (non-http protocol)
(1) I won’t talk about new semantic tags.
For example <footer></footer>
(2) Enhanced form form 2.0
one,1) Comparison between new input type h4 and h5!
Input type in H4: text /password /radio /checkbox/ sybmit/ reset / file /hidden / image/
Input type in H5: email/url/number/tel/search /range /color/month/week /date
2) New form elements
Form elements in H4: input/textarea/select, option/label
New form elements in H5: datalist/progress/meter/output
2. New form element in h5--datalist suggestion list<datalist id=lunchList> <option>Shredded Pork with Beijing Sauce</option> <option>Pork in Guobao</option> <option>Shredded Pork with Fish Flavor</option> <option>Shredded Pork with Green Pepper</option> <option >Di Sanxian</option></datalist>
Please enter the lunch you need :<input type=text name=lunch list=lunchList/>
There are two forms:
There is a progress plug-in style in bootstrap
<form> Network connection<progress></progress> <br/> <!-- Between 0-1--> Download progress <progress id=p3 value=0></progress> <input type=number value =1></form><script type=text/javascript> /*The difference between settimeout and setInterval is that settimeout is executed once, and setInterval is executed every other time*/ var t=setInterval(function(){ var v = p3.value; v += 0.1; p3.value = v; if(v>=1){ clearInterval(t); alert(download completed); } },500); </script>5. New form element in h5-meter
<body> Oil content: <meter id=m1 min=0 max=100 low=30 high=70 optimum=40 value=50></meter> PM value: <meter id=m2 min=0 max=500 low= 100 high=300 optimum=150 value=750></meter></body>
Meter: Weights and measures/scale/, used to mark a range: unacceptable (red)/acceptable (yellow)/very good (green)
<meter min=可取的最小值max=可取的最大值low=合理的下限值high=合理的上限值optimum=最佳值value=当前值></meter>
3) New attributes of form elements
1. Attributes of form elements in H4: <input>
id/class/title/type/value/name/style/readonly/disabled/checked/
New attributes of form elements in H5
1) placeholder: placeholder characters cannot be submitted as prompts
<input value=tom placeholder=请输入用户名/>
2) autofocus: Automatically obtain input focus (you can enter without clicking. Only the first input setting is valid)
<input autofocus>
3) multiple: multiple input values are allowed to appear in the input box, separated by commas [email protected], [email protected]
<input type=email name=emails multiple>
4) form: used to place the input field outside the FORM
<form id=f5></from>
<input form=f5>
=================New properties related to input validation============================ =======
For an example, see input validation related attributes/yz.html
5)required: required, the content cannot be empty
6) maxlength: Specify the maximum length of the string
7) minlength: Specify the minimum length of the string
8) max: the maximum value of the specified number
9) min: the minimum value of the specified number
10) pattern: Specify the regular expression that the input must match
The above validation attributes will affect the validity attribute of the js object corresponding to the form element, and the validity attribute is the attribute of verification.
(3) video video and audio
1. In what aspects is flash replaced by H5 reflected?flash drawing (AS/FLEX) =>Canvas/SVG
flash animation => timer+Canvas
Video and audio playback => VIDEO/AUDIO
flash client storage => WebStorage
2.H5 new feature - video player (it is an inline block element. You can give width and height)H5 provides a new tab for playing videos:
<video src=></video> <video src=> <source src=res/birds.mp4></source> <source src=res/birds.ogg></source> <source src=res/birds. webm></source>
Your browser does not support VIDEO playback!
</video> It itself is a 300*150 inline block element. Note: The multi-line source is written to be compatible with various browsers. Because browsers do not support video formats uniformly. Some browsers, such as some browsers, support mp4 format. Then it will play the first video in mp4 format. If it does not support it, check whether it supports the following ogg video. If it supports it, then it will Play, if it is not supported, continue down. There is no source below, then it means that your browser does not support VIDEO playback! .
Commonly used members of VIDEO tag/object:
Member properties:
<video id=v2 src= autoplay controls loop muted poster=2.jpg preload=auto></video>
autoplay: false, whether to automatically play, default false controls: false, whether to display playback controls, the default is false loop: false, whether to loop playback, the default is false muted: false, whether to mute playback, the default is false poster: '', playing The poster displayed before the first frame, which can be an image. The default is empty and no preload: video preloading strategy, possible values: auto: preloads the metadata of the video and a certain buffering time. It must not be used on the mobile phone (size/duration. First frame content, buffering time) (pre Loading wastes traffic) metadata: only preloads the metadata of the video (size/duration, first frame content,) no buffering duration, suitable for mobile phones none: does not preload any data
-------------------------------------------------- --------------- The attribute usage of id v2 is for example:
v2.playbackRate=3;
currentTime: current playback duration duration: total duration paused: true, whether the current video is in a paused state, true means paused, false means playing volume: 1 The default value is 1, current volume playbackRate: 1, playback rate greater than 1 means fast playback, less than 1 means slow playback
id v2 method:
play(): play the video pause(): pause the playback member event: onplay: an event triggered when the video starts playing onpause: an event triggered when the video is paused Practice: Customize the play/pause button without using the controls that come with the video Move the mouse out of the video area to hide the button; move the mouse into the display button. For example: video audio, canvas/video.html When paused, the advertisement will be displayed, and when the mouse is played, the advertisement will be hidden.
3. H5 new feature-audio player
<audio src=></audio><audio src=><source src=res/birds.mp3></source><source src=res/birds.ogg></source><source src=res/birds. wav></source>
The attribute method is the same as the video, except that there is no poster attribute*** to determine whether the check box is selected
cb.onchange=function(){ this.checked true means selected, false means not selected}
(4), canvas
There is only one brush object on each canvas - called the drawing context object - use this object to draw!
var ctx = canvas.getContext('2d') //现在只有2d的得到画布上的画布对象
Canvas drawing---difficulty! ! !
1) SVG drawing: vector drawing technology, which appeared in 2000 and was later incorporated into the H5 standard. 2) Canvas drawing: bitmap drawing technology, a drawing technology proposed by H5. 3) WebGL drawing: 3D drawing technology, which has not yet been incorporated into the H5 standard.
canvas drawing technology canvas: canvas, H5 implements 2D drawing technology
<canvas width=500 height=400>您的浏览器不支持canvas</canvas>
The canvas tag is an inline-block of 300*150 by default in the browser. The width and height of the canvas can only be assigned using HTML/JS attributes, not CSS styles! There is only one brush object on each canvas - called the drawing context object - use this object to draw! var ctx = canvas.getContext('2d') //Now only 2d gets the canvas object on the canvas
1) Use canvas to draw a rectangle
Draw a rectangle
ctx.lineWidth = 1 Stroke width ctx.fillStyle='#000' Fill style color ctx.strokeStyle='#000' Stroke style color ctx.fillRect(x,y,w,h); //Fill a rectangle x , y coordinate w, h width and height ctx.strokeRect(x,y,w,h); //Stroke a rectangle ctx.clearRect(x,y,w,h) Clear all drawings within a rectangle
2) Use canvas to draw text
The anchor point of a piece of text is at the beginning of its text baseline
ctx.textBaseline = 'alphabetic' //The default value of the text baseline is the third line ctx.font=12px sans-serif //Font size and style ctx.fillText(str,x,y) //Fill ctx.strokeText(str ,x,y) //Stroke a piece of text ctx.measureText(str) //Set the measurement text based on the current text size and font, and the returned object is {width: x}
3) Use canvas to draw paths
Path: Similar to the pen tool in PS, it is an arbitrary shape composed of multiple coordinate points. The path is invisible and can be used for stroke, filling, and cropping.
ctx.beginPath() //Start a new path ctx.closePath() //Close the current path ctx.moveTo(x,y) //Move to the specified point ctx.lineTo(x,y) //From the current point to the specified point Draw a straight line ctx.arc(cx,cy,r,start,end); //Draw an arch path//cx cy is the center coordinate of the circle xy r is the radius, start is the starting angle, and end is the ending angle
Angle: 360 = Radians: 2PI 180 = 1PI For example
ctx.arc(100,200,30,0,2*Math.PI)ctx.stroke(); //Current path stroke ctx.fill(); //Current path fill ctx.clip();//Use current path Crop //************The corner of the connection**********ctx.lineJoin='miter' //A sharp corner appears at the connection of the line ctx.lineJoin='round ' //Rounded corners appear at the connection of the line ctx.lineJoin = 'bevel' //Square corners appear at the connection of the line
4) Use canvas to draw images
Canvas is a client-side technology, and the image is in the server, so the browser must first download the image to be drawn and wait for the image to be loaded asynchronously:
var img = new Images();img.src='x.png';console.log(img.width); //0 Asynchronous request for images img.onload=function(){console.log(img.width,img .height); //Value image loading is completed //Start drawing the image onto the canvas ctx.drawImage(img,x,y); //Original size drawing ctx.drawImage(img,x,y,w,h); //Set width and height}
Listen to mouse movement events above the canvas
ctx.onmousemove = function(e){x=e.offsetX;y=e.offsetY;console.log(x,y);}
2. Gradient in canvas drawing
Linear gradient: linearGradient Radial gradient: radialGradient You can refer to the gradient effect in ps,
var g = ctx.createLinearGradient(x1,y1,x2,y2);g.addColorStop(0,'#f00');g.addColorStop(0.5,'#ff0');g.addColorStop(1,'#0f0' );ctx.strokeStyle=g;
Difficulty: There are many coordinate axes and words in the coordinate system
3. Drawing deformation
ctx.rotate(radians) //Rotate the drawing context object (i.e. brush), the axis point is the origin of the canvas ctx.translate(x,y) //Translate the origin of the entire canvas to the specified point ctx.sava(); / /Save all the current deformation status values of the brush (from the save in the game) ctx.restore(); //Restore the deformation status of the brush to the most recent save (read the save in the game) ctx.save(); //Save the original first status var deg = 10*Math.PI/180; //The angle to be rotated is rotated 10 degrees ctx.rotate(deg); //Rotated ctx.drawImage(img,0,0); //Drawing pictures, what to draw if the brush is crooked They are all crooked ctx.restore(); // The original state saved when taking out the save
(5) SVG drawing
Let’s first understand what bitmaps and vectors are. Just understand it briefly.
Bitmap: It is composed of pixels one after another, each point has its own color, and the color is delicate. Vector graphics: composed of lines one after another. Each line can specify a color, direction, and can be infinitely scaled, but the color details are not rich enough.
1. SVG drawing uses tags for drawing, and you can directly bind event listeners
<svg width=300 height=200 xmlns=http://www.w3.org/2000/svg> <rect width=100 height=100></rect></svg>
2. How to create an svg tag using js!
//var r1 = document.createElement('rect'); This svg element cannot be created because it has an age limit and namespace (that is to say, if this does not work, use the following method to create it!!!!) var r1= document.createElementNS('http://www.w3.org/2000/svg','rect');r1.setAttribute('width','50');r1.setAttribute('height',300);s1 .appendChild(r1);
3. Create ellipse with svg
<svg width=300 height=200 id=c6> <ellipse rx=100 ry=40 cx=100 cy=100 fill=#faa stroke=#a00></ellipse></svg>
4. Create a straight line in svg
<svg width=300 height=200 id=c6> <line x1=0 y1=0 x2=100 y2=200 stroke=#000 stroke-width=50 stroke-linecap=square></line></svg>
Note: stroke-linecap=square will produce more squares, stroke-linecap=round will produce more circular areas, stroke-linecap=butt will not produce more squares (that is to say, the straight line you create has a difference between the beginning and the end of these attributes! Try it yourself and you’ll find out! Details are important!)
5. Create polyline using svg
<svg width=300 height=200 id=c6> <polyline points=50,50 100,300 150,100></polyline> //What comes out is a triangle <polyline points=50,50 100,300 150,100 fill=transparent stroke=#000>< /polyline> //What comes out is a polyline</svg>
6. Geolocation (In the future, we don’t need a client, we can also locate ourselves!)
Geolocation: Geolocation, using JS to obtain the geographical coordinates (longitude, latitude, altitude, speed) data of the current browser, used to implement LBS applications (Location Based Service), such as Ele.me, Amap Navigation...
How mobile browsers obtain location information:
1) The first choice is the GPS chip in the mobile phone and satellite communication, the positioning accuracy is within meters 2) The second choice is the mobile phone base station for positioning acquisition, the positioning accuracy is within kilometers (illegal) How to obtain positioning information through a PC browser: 1) Reverse through IP address Parsing and positioning accuracy depend on the size of the IP address database
HTML5 provides a new object for obtaining the current browser's positioning information:
window.navigator.geolocation{ getCurrentPosition:fn, //Get current positioning information watchPosition:fn, //Monitor changes in positioning data clearWatch:fn //Cancel monitoring}
2. Extension: How to embed Baidu Map in a web page
1) Register a Baidu developer account map.baidu.com ---> lbsyun.baidu.com 2) Create a website; log in to Baidu Map and apply for a map AccessKey for the website 3) Embed the map provided by Baidu Map in your own web page API, embedded in Baidu map
I won’t talk much about how to embed this here! (Remember that you must register an account to use Baidu Maps, and then just quote other people’s libraries!)
7. Drag and drop API
I mentioned drag and drop before: friends, go ahead and find previous blogs by yourself.
eight storage
Storage mainly consists of cookies and sessions (I will explain the differences and precautions when looking for a lot of writing methods earlier): Remember that sessions disappear when you close the browser, and cookies do not disappear when you close the browser! Note: Time must be added when the cookie is stored. If no time is added, it will disappear after closing the browser! This browser storage can be used to solve many functional problems, such as remembering passwords and other functions! !
Nine web Sockets
Should we talk about this? . . . . Let’s talk about it briefly, it all depends on understanding~~
Web socket is a non-http two-way connection that can be established between the server and the client!
This connection is real-time and permanent.
The server can actively push messages.
The server no longer needs to poll the client for requests, and communication between the server and the client does not require re-establishing the connection.
That is, sustainable back-and-forth communication.
How to create it? One piece of code is done
var webSocket = new WebSocket (ws://localhost:8005/socket); //url must start with ws or wss text: because it is not http, it is websocket, it is your own identification, encrypted transmission, just remember it. webSocket.send() //Send text data, only text can be sent. (Use json object to convert js object into text data before sending) webSocket.close();//Close and cut off the communication connection. webSocket.onmessage= function(event){ var data=event.data;} // Receive messages from the server webSocket.onopen =function(event){ //Processing when starting communication} webSocket.onclose =function(event) { //Processing at the end of communication}Summarize
The above is a comprehensive list of the new features and usage of HTML5 introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank everyone for your support of the VeVb martial arts website!