preface

Learning the Definitive Guide to HTML5 and CSS3 was a great book, and after learning it, I felt that the web world was much more enlightened. This book is needed for web front-end development engineers with some foundation.

This book focuses on HTML5 and CSS3, as can be seen from the title of the book. First, learn new syntax and markup methods, new elements and apis in HTML5.

Readers understand the content:

In addition to HTML5, there is CSS3 to learn, which has all kinds of new styles and attributes.

The book also owes a lot to the author and staff.

The book also has examples of using new structural elements in HTML5 to build web pages and using HTML5+ CSS3 to build Web applications.

Since 2010, HTML5 has been widely supported by browsers around the world and is very popular in the industry. So do you need to understand the general differences between HTML5 and previous versions, and why HTML5 is supported, the answer is that you don’t really need it to work.

But for example, a front-end you can type out the code, but the question is do you know what a cookie is? Maybe you get the general idea. Your team leader or senior manager asks you what a cookie is. Sometimes most people are a dizzy, however, Baidu check can know the answer.

In fact, need to know about HTML5

The emergence of HTML5 even Microsoft has made standard improvements for the next generation of Internet Explorer 9 in order to support HTML5.

Examples of HTML4 code:

User name:

Sample code:

<form> <p><label> user name: <input name="search" type="text" id="search"></label></p> <script type="text/javascript"> document.getElementById("search").focus(); </script> </form>Copy the code

Examples of HTML5:

<form> <p><label>Search:<input name="search" autofocus></label></p> </form> <div id="header">... </div> <div id="nav">... </div> <div class="arcticle">... </div> <div id="side-bar">... </div> <div id="footer">... </div>Copy the code

The purpose of the HTML 5

HTML5 came out to be able to build simpler Web applications, let programmers write simpler HTML code, HTML5 provides a lot of apis, new attributes, new elements and so on, so THAT HTML5 has a reason to be popular.

SessionStorage and globalStorage, which replace cookies in HTML5, are now supported in IE8.

When a new version appears, many people will have questions, worrying about whether it will produce errors and so on. Though? It has its reasons for being popular.

  1. compatibility
  2. practical
  3. Non-revolutionary development

HTML5 has come out and solved all sorts of problems, and this is a more powerful version.

ContentEditable, designMode, Hidden, SpellCheck, tabIndex.

HTML5

ContentType ContentType or text/ HTML

DOCTYPE declaration, in HTML5 DOCTYPE declaration method as follows, case insensitive:

<meta charset="UTF-8" http-equiv="Content-Type" content="text/html; charset=UTF-8">

Code examples:

checkbox checkbox1 checkbox2 checkbox3

Code:

<input type="checkbox" checkbox>checkbox
<input type="checkbox">checkbox1
<input type="checkbox" checked="checked">checkbox2
<input type="checkbox" checked="">checkbox3
Copy the code

Examples of HTML5 markup:

<! DOCTYPE html> <meta charset="UTF-8"> <title>html5</title> <p>html5 <br/>html5Copy the code

The new element

The section element represents a content block in the page.

The article element represents a piece of context-independent content in a page.

Aside element, supporting information related to the content of an article element in addition to the content of the article element.

Header element, representing a content block or the title of the entire page.

The hGroup element is used to combine the title of an entire page or a content block within the page.

The footer element represents a footnote for the entire page or a content block within the page.

The nav element, which represents the portion of the page that navigates the link.

Figure element, representing a separate stream content, typically a separate unit within the document body stream content.

Effect:

web

web

Code:

<figure>
<figcaption>web</figcaption>
<p>web</p>
</figure>
Copy the code

The video element defines the video.

The audio element defines the audio.

Embed element, used to insert various multimedia.

The Mark element is used to visually present the user with text that needs to be highlighted or highlighted.

The progress element represents a running process.

The time element, representing a date or time.

Ruby elements that represent Ruby annotations.

The RT element represents the interpretation or pronunciation of a character.

The RP element, which is used in Ruby annotations to define what is displayed in browsers that do not support Ruby elements.

The WBR element represents a soft newline.

The Canvas element represents graphics, such as charts and other images.

Effect:

Code examples:

<canvas style="background-color: red;" id="myCanvas" width="100" height="100"></canvas>
Copy the code

The command element represents a command button, such as a radio button, check box, or button.

Code:

<command onclick="cut()" label="cul">
Copy the code

The Details element represents the details that the user requires and can obtain.

HTML – details

web

Code:

<details> <summary> HTML - Details </summary> Web </details>Copy the code

The datalist element, representing alist of optional data

The datagrid element represents a list of optional data, which is displayed as a tree.

The keygen element represents the production key.

The output element represents different types of output, such as the output of a script.

The source element represents the media resource used to define the media element.

The menu element represents the menu list.

Effect:

  • web
  • it
  • Code:

    <menu>
     <li><input type="checkbox"/>web</li>
     <li><input type="checkbox"/>it</li>
    </menu>
    Copy the code

    inputThe type of the new element

    Email Indicates the text box in which an E-mail address must be entered.

    Url Indicates the text field in which the URL address must be entered.

    Number represents a text input field in which numeric values must be entered.

    Range represents a text input field in which numeric values must be entered within a range.

    Date Pickers

    Date – Select the day, month, and year

    Month – Selects month and year

    Week – Selects the week and year

    Time – Select time, day, month, year

    Datetime – Select time, day, month, year

    Datetime-local – Select time, day, month, year

    Html5 no longer supports the Frame frame, only the IFrame frame.

    New form properties

    The multiple attribute allows multiple files to be uploaded at once.

    Added the novalidate attribute to input, button, and form elements, which eliminates the check on submission and allows forms to be submitted unconditionally.

    Add reversed for the OL element to indicate that the list is displayed in reverse order.

    The meta element adds the charset attribute.

    The menu element adds two new attributes — Type and label.

    Add the scoped attribute to the style element to specify the scope of the style.

    Adds an async attribute to the script element, which defines whether the script is executed asynchronously.

    Global properties

    The contentEditable property allows the user to edit the content of an element that has mouse focus and, after clicking the mouse, provides a caret indicating that the content of the element is editable.

    In addition to the contentEditable property, the element has an isContentEditable property, which is true when the element is editable and false when it is not.

    Example:

    <ul contentEditable="true"> <li> Element 1</li> </ul>Copy the code

    DesignMode property, indicating whether the entire page is editable. Using a JavaScript script to specify the designMode attribute is as follows: document.designMode=”on”.

    Hidden property, all elements are allowed to use a hidden property. This property is similar to the hidden element in the input element and is used to render the element, leaving it invisible.

    The spellCheck property checks the spelling and grammar of the text entered by the user. The spellCheck property is a Boolean property with true and false values.

    Tabindex property, when repeatedly hitting the TAB key in the window or the control in the page to get the focus, all the controls in the window or the page are traversed, the tabIndex of each control indicates the number of the control to be accessed.

    HTML 5 new

    Article, section, nav, aside, header, hGroup, footer, address.

    The article element represents a single, complete piece of content in a document, page, or application that can be referred to externally by itself.

    The article example:

    < article > < header > < h1 > web < / h1 > < / p > < p > date < header > < footer > < p > web < / p > < footer > < article >Copy the code

    The aside element is used to represent the attached information section of the current page or article.

    The time element represents a time or date in a 24-hour period and allows time difference.

    The pubdate attribute is an optional, Boolean attribute used on the time element of the article element.

    Code:

    <header><h1> Page title </h1></header>Copy the code

    The hGroup element is the element that groups headings and their subheadings.

    The footer element can be used as a footnote to its parent content block or a root block.

    Code:

    <div id="footer">
    <ul>
     <li>web</li>
    </ul>
    </div>
    Copy the code

    Content block arrangement can be divided into “display arrangement” and “implicit arrangement”.

    Forms and files

    Form property example

    Sample code:

     <form id="testform">
     <input type="text">
     </form>
     <textarea form="testform"></textarea>
    Copy the code

    Formaction binds properties

    Formaction, adding this property differently, allows you to click different buttons to submit the form to different pages.

    formmethodattribute

    There is also only one method attribute within each form to specify a uniform submission method. In HTML5, you can use the formation attribute to specify a different submission page for each form element, and you can use the FormMethod attribute to specify a different submission method for each form element.

    Placeholder refers to the input prompt displayed when the text box is in the uninput state, and the autofocus attribute automatically takes the cursor focus.

    <input type="text" autofocus>
    Copy the code

    The autocomplete property, the autocomplete feature used for auxiliary input.

    The input element, search for a search, tel for a phone, URL for entering a URL format, email for entering text in email format, number for a numeric input text box, and range allows only text boxes with a range of values. Color Color selection text box. File Text Select the text box.





































    Code:

    <input name="url" type="url" value="http://www.microsoft.com"> <br/> <input name="email" type="email" value="[email protected]"> <br/> <input name="date" type="date" value="2020-02-02"> <br/> <input name="time" type="time"  value="10:00"> <br/> <input name="datetime" type="datetime"> <br/> <input name="datetime-local" type="datetime-local"> <br/> <input name="month" type="month" value="2010-10"> <br/> <input name="week" type"week" value="2010-w40"> <br/> <input name="number" type="number" value="23" min="10" max="100" step="5"> <br/> <input name="range" type="range" value="30" min="0" max="100" step="5">Copy the code

    The append to the output element, defining different types of output.

    Code:

    <input name="range1" type="range" min="0" max="100" step="5"/>
    <output onforminput="value=range1.value">50</output>
    Copy the code

    Required property, which tells the user that something must be entered in this element.

    The pattern attribute, which requires the input to conform to a certain format.

    The step property controls how far a value increases or decreases in an element.

    Explicit validation, the checkValidiity method, which is called to explicitly validate all or a single element content in the form.

    The cite element represents the title of the work.

    The file control allows only one file, the multiple property, and the File control allows multiple files to be placed at once. The FileList object is a list of file objects. It represents all files selected by the user.

    A Blob object

    Blob objects represent binary raw data and provide a slice method. Blob objects have two properties, the size property representing the length of a BLOb object in bytes, and the type property representing the MIME type of the blob.

    Blob object usage example

    var file; File = document.getelementById ("file").files[0]; var size = document.getElementById("size"); // Display file bytes size.innerhtml =file.size; var type=document.getElementById("type"); // Display the file type type.innerhtml =file.type;Copy the code

    Code:

    <input type="file" id="file" accept="image/*"/>
    Copy the code

    The FileReader interface is used to read files into memory and read data from files.

    if(typeof FileReader == 'undefined'){
        alert("web")
    }else{
        var reader = new FileReader();
    }
    Copy the code

    The following types of MIME support drag processing:

    Text /plain: indicates text text

    Text/HTML: HTML text

    Text/XML: INDICATES the XML text

    Text /uri-list: indicates the list of urls. Each URL contains one line.

    The canvas element

    Canvas elements are very important for drawing graphics and images.

    The Canvas element specifies the id, width, and height attributes.

    In the body property, onload=”draw(‘canvas’);” Statement, call the draw function in the script file to draw the graph.

    When drawing with the Canvas element.

    1. achievecanvasElements,document.getElementByIdAnd so oncanvasObject.
    2. To get a context for drawing graphics, you need to use the graphics context, which is an object that encapsulates many drawing functionscanvasThe object’sgetContextMethod to get the graphics context.
    3. Fill and draw the border, fill asfill, draw the borderstroke. Fill means to fill the interior of the graph, and draw border means to draw only the border of the graph.
    4. Set drawing styles primarily for, but not limited to, the colors of graphics. First, set the style of the fill shape,fillStyleProperty, the style of the fill, the color value to fill in the property. Second, set the style of the border of the graphic,strokeStyleProperty, the style of the graphic border, in which the border color value is filled.
    5. Specifies the line width, using the graphics context objectlineWidthProperty to set the width of the graphic border. When drawing a graph, any line can pass throughlineWidthProperty to specify the width of the line.
    6. Specify the color value, the fill color and the border color pass separatelyfillStyleProperties andstrokeStyleProperties. (rgb(red, green, blue) orrgba(Red, green, blue, lightness).
    7. Draw a rectangle usingfillRectMethods andstrokeRectMethod to fill a rectangle and draw a rectangle border.

    context.fillRect(x,y,width,height) context.strokeRect(x,y,width,height)

    The origin is the top left corner of the canvas

    Code examples:

    <script> function draw(id) { var canvas = document.getElementById(id); if(canvas == null){ return false; } var context = canvas.getContext('2d'); context.fillStyle="#EEEEFF"; ,0,400,300 context. FillRect (0); context.fillStyle="red"; context.strokeStyle="blue"; context.lineWidth=1; The context. FillRect (50,50,100,100); The context. StrokeRect (50,50,100,100); } </script>Copy the code

    The clearRect method erases the graphics in the specified rectangular region, making all the colors in the rectangular region transparent.

    context.clearRect(x,y,width,height)

    Code:

    <! DOCTYPE html> <html> <head> <meta charset=utf-8> <meta name=description content=""> <meta name=viewport content="width=device-width, initial-scale=1"> <title>1</title> </head> <body> <canvas id="canvasId"></canvas> <script> var canvas = document.getElementById('canvasId'); if(canvas == null){ return false; } var context = canvas.getContext('2d'); context.fillStyle="#EEEEFF"; ,0,400,300 context. FillRect (0); var n = 0; for(var i=0; i<10; i++){ context.beginPath(); Context. The arc (I * I * 25, 25, I * 10, 0, math.h PI * 2, true); context.closePath(); The context. The fillStyle = 'rgba (255,0,0,0.25); context.fill(); } </script> </body> </html>Copy the code

    Graphic drawing:

    • Using a graphics context objectbeginPathMethods:context.beginPath(), this method takes no arguments. Call this method to begin the creation of the path.
    • context.arc(x,y,radius,startAngle,endAngle,anticlockwise)Create circular paths.

    Radius is the prototype radius, startAngle is the startAngle, endAngle is the endAngle, anticlockwise is whether to draw clockwise.

    Arc method can be used to draw a circle, and draw an arc, the beginning Angle and the end Angle determine the radian, anticlockwise parameter is a Boolean parameter. True draws in sequence, false draws counterclockwise.

    • Close the path using the graphics context objectclosePathMethod to close the path.context.closePath(), this step is just the creation of the path, and does not draw any graphics.
    • Draw style,The context. The fillStyle = 'rgba (255,0,0,0.25);

    moveToandlineTo

    The moveTo method moves the cursor to a specified point from which to draw a line. MoveTo (x,y), where x is the abscissa and y is the ordinate.

    The lineTo method draws a line from the starting point of the line specified in the moveTo method to the end point of the line specified in the argument.

    LineTo (x,y), x represents the abscissa of the end line,y represents the ordinate of the end line.

    Bezier curve

    Bezier curves are drawn using the bezierCurveTo method

    Definition of this method:

    context.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y);

    It has six parameters. Two control points are needed to draw bezier curve, cp1, CP2, x and y are the horizontal and vertical coordinates of the curve end point respectively.

    Example of drawing bezier curve:

    The effect

    Code:

    <! DOCTYPE html> <html> <head> <meta charset=utf-8> <meta name=description content=""> <meta name=viewport content="width=device-width, <canvas id="can"> </canvas> </canvas> </canvas> <script> function draw(){ var canvas = document.getElementById('can') if(canvas == null){ return false; } var context = canvas.getContext('2d'); context.fillStyle = '#EEEFF'; ,0,400,300 context. FillRect (0); var n = 0; var dx = 150; var dy = 150; var s = 100; context.beginPath(); context.globalCompositeOperation = 'and'; The context. The fillStyle = 'RGB (100255100); var x = Math.sin(0); var y = Math.cos(0); var dig = Math.PI / 15 * 11; context.moveTo(dx,dy); for(var i=0; i<30; i++) { var x = Math.sin(i * dig); var y = Math.cos(i * dig); context.bezierCurveTo(dx+x+s,dy+y*s-100,dx+x*s+100,dy+y*s,dx+x*s,dy+y*s); } context.closePath(); context.fill(); context.stroke(); } </script> </body> </html>Copy the code

    QuadraticCureTo method is used to draw quadratic spline curves.

    Context. QuadraticCurveTo (in float CPX,in float cpy,in float x,in float y).

    Quadratic splines are easier to draw than Bezier curves, which require two control points, and Bezier curves require only one control point.

    Draw gradient graph

    Draw linear gradient

    The fillStyle method can fill the color as well as specify the object to fill.

    Gradient: A gradual transition from one color to another when filling.

    A linear gradient between two points

    context.createLinearGradient(xStart, yStart, xEnd, yEnd);

    Use four parameters.

    Use this method to create a LinearGradient object that uses two coordinate points. Use the addColorStop method to set the color of the gradient.

    context.addColorStop(offset, color);

    The value of offset is a floating point value in the range 0 to 1. The gradient starts at an offset of 0 and ends at a point of 1. It is the offset of the set color from the beginning of the gradient.

    Gradient, you need to append two colors by using the addColorStop method at least twice.

    HTML5 Canvas fillRect() method

    Draw a 150*100 pixel filled rectangle:

    The fillRect() method draws a “filled” rectangle. The default fill color is black.

    JavaScript:

    var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); CTX. FillRect,20,150,100 (20);Copy the code

    JavaScript syntax:

    context.fillRect(x,y,width,height);

    The parameter value

    parameter describe
    x The x-coordinate of the top left corner of the rectangle
    y The y-coordinate of the top left corner of the rectangle
    width Width of rectangle, in pixels
    height The height of the rectangle, in pixels

    HTML5 Canvas createLinearGradient() method

    Define a gradient from black to white (from left to right) as the fill style for the rectangle:

    JavaScript:

    var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); Var GRD = CTX. CreateLinearGradient,0,170,0 (0); grd.addColorStop(0,"black"); grd.addColorStop(1,"white"); ctx.fillStyle=grd; CTX. FillRect,20,150,100 (20);Copy the code

    The createLinearGradient() method creates a linear gradient object.

    JavaScript syntax:

    context.createLinearGradient(x0,y0,x1,y1);

    The parameter value

    parameter describe
    x0 The x coordinate of the beginning of the gradient
    y0 The y coordinate of the beginning of the gradient
    x1 The x-coordinate of the end of the gradient
    y1 The y-coordinate of the end point of the gradient

    Define a rectangle filled with blue:

    JavaScript:

    var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.fillStyle="#0000ff"; CTX. FillRect,20,150,100 (20);Copy the code

    Gradient effect:

    Code:

    <! DOCTYPE html> <html> <head> <meta charset=utf-8> <meta name=description content=""> <meta name=viewport content="width=device-width, <canvas id="can"> </canvas> </canvas> </canvas> <script> function draw(){ var canvas = document.getElementById('can') if(canvas == null){ return false; } var context = canvas.getContext('2d'); Var g1 = context. CreateLinearGradient,0,0,300 (0); G1. AddColorStop (0, 'RGB (255255, 0)); G1. AddColorStop (1, 'RGB (0255255)); context.fillStyle=g1; ,0,400,300 context. FillRect (0); var n = 0; Var g2 = context. CreateLinearGradient,0,300,0 (0); G2. AddColorStop (0, 'rgba,0,255,0.5 (0)); G2. AddColorStop (1, 'rgba (255,0,0,0.5)); for(var i=0; i<10; i++){ context.beginPath(); context.fillStyle = g2; Context. The arc (I * I * 25, 25, I * 10, 0, math.h PI * 2, true); context.closePath(); context.fill(); } } </script> </body> </html>Copy the code

    Draw radial gradient

    Radial gradient: A gradient that spreads out along the radius of a circle.

    Draw using the createRadiaGradient method of the graph context object.

    context.createRadiaGradient(xStart,yStart,radiusStart,xEnd,yEnd,radiusEnd);

    You need to use six parameters.

    parameter describe
    xStart The gradient begins with the abscissa of the center of the circle
    yStart The gradient begins at the center of the circle
    radiusStart The radius of the starting circle
    xEnd The gradient ends the abscissa of the circle center
    yEnd Gradient end prototype ordinate
    radiusEnd End radius of the circle

    To set the color, use the addColorStop method. Similarly, a floating point number between 0 and 1 is used as the offset of the gradient turning point.

    Draw radial gradient effect:

    Use the createRadialGradient method and the addColorStop method:

    HTML5 Canvas beginPath() method

    Draw two paths on the canvas; Red and blue:

    Definitions and Usage

    The beginPath() method starts a path, or resets the current path.

    Start a path and move to position 0,0. Create a line at position 300,150:

    JavaScript:

    var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.beginPath(); CTX. MoveTo (0, 0); CTX. LineTo (300150); ctx.stroke();Copy the code

    JavaScript:

    var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.beginPath(); ctx.lineWidth="5"; // Set line thickness property ctx.strokeStyle="red"; // red path ctx.moveto (0,75); CTX. LineTo (250,75); ctx.stroke(); // draw ctx.beginPath(); ctx.strokeStyle="blue"; // blue path ctx.moveto (50,0); CTX. LineTo (150130); ctx.stroke(); // DrawCopy the code

    Draw radial gradient effect:

    Code :(note spelling)

    <! DOCTYPE html> <html> <head> <meta charset=utf-8> <meta name=description content=""> <meta name=viewport content="width=device-width, <canvas id="can"> </canvas> </canvas> </canvas> <script> function draw(){ var canvas = document.getElementById('can') if(canvas == null){ return false; } var context = canvas.getContext('2d'); Var g1 = context. CreateRadialGradient,0,0,400,0,400 (400); G1. AddColorStop (0.1, 'RGB (255255, 0)); G1. AddColorStop (0.3, 'RGB (255,0,255)); G1. AddColorStop (1, 'RGB (0255255)); context.fillStyle=g1; ,0,400,300 context. FillRect (0); var n = 0; Var g2 = context. CreateRadialGradient,0,250,250,300 (250250); G2. AddColorStop (0.1, 'rgba (255,0,0,0.5)); G2. AddColorStop (0.7, 'rgba (255255,0,0.5)); G2. AddColorStop (1, 'rgba (0,0,255,0.5)); for(var i=0; i<10; i++){ context.beginPath(); context.fillStyle = g2; Context. The arc (I * I * 25, 25, I * 10, 0, math.h PI * 2, true); context.closePath(); context.fill(); } } </script> </body> </html>Copy the code

    Draw deformation graph

    Coordinate transformation

    Deformation: This can be achieved by using the Canvas API’s axis transformation processing function.

    Draw a graph. By default, the top left corner of the Canvas corresponds to the origin of the coordinate axes. That’s 0,0.

    Coordinate processing, you can realize the deformation of the graph.

    Three ways:

    1. translation
    2. expand
    3. rotating

    Translation: Moves the origin of the coordinate axes using the Translate method of the graphics context object.

    Context.translate (x,y), x,y is how many units to move.

    Enlarge: Magnifies the graph using the scale method of the graph context object.

    Context. scale(x,y), where x and y are the magnifications in this direction.

    Rotate: Rotate the graph using the Rotate method of the graph context object.

    Method: context.rotate(Angle), where Angle is the rotation Angle in the clockwise direction and anticlockwise is a negative value.

    Example of coordinate transformation:

    Code:

    <! DOCTYPE html> <html> <head> <meta charset=utf-8> <meta name=description content=""> <meta name=viewport content="width=device-width, <canvas id="can"> </canvas> </canvas> </canvas> <script> function draw(){ var canvas = document.getElementById('can') if(canvas == null){ return false; } var context = canvas.getContext('2d'); context.fillStyle = '#EEEEFF'; ,0,400,300 context. FillRect (0); Context.translate (200,50); The context. The fillStyle = 'rgba (255,0,0,0.25); for(var i=0; i<50; I++) {context. Translate (25, 50); Context. Scale (0.95, 0.95); context.rotate(Math.PI/10); ,0,100,50 context. FillRect (0); } } </script> </body> </html>Copy the code

    Transform the image drawn using paths

    Learn the Translate,scale, and Rotate methods.

    Effect: Use coordinate transformation and path together

    Code:

    <! DOCTYPE html> <html> <head> <meta charset=utf-8> <meta name=description content=""> <meta name=viewport content="width=device-width, <canvas id="can"> </canvas> </canvas> </canvas> <script> function draw(){ var canvas = document.getElementById('can') if(canvas == null){ return false; } var context = canvas.getContext('2d'); context.fillStyle = '#EEEEFF'; ,0,400,300 context. FillRect (0); Context.translate (200,50); for(var i=0; i<50; I++) {context. Translate (25, 50); Context. Scale (0.95, 0.95); context.rotate(Math.PI/10); create5Star(context); context.fill(); } } function create5Star(context){ var n = 0; var dx=100; var dy=0; var s=50; context.beginPath(); The context. The fillStyle = 'rgba (255,0,0,0.5); var x = Math.sin(0); var y = Math.cos(0); var dig =Math.PI/5*4; for(var i=0; i<5; i++){ var x =Math.sin(i*dig); var y =Math.cos(i*dig); context.lineTo(dx+x*s,dy+y*s); } context.closePath(); } </script> </body> </html>Copy the code

    Matrix transformation

    Using matrix transformation to achieve deformation technology

    Transforms the transformation matrix using the Transforms method of the graphics context object

    context.transform(m11, m12, m21, m22, dx, dy)

    parameter describe
    dx Move the origin x to the right on the x axis
    dy I’m going to move the origin down y

    Matrix methods need to be re-documented for further study. The three methods mentioned in the previous graph distortion actually modify the transformation matrix implicitly.

    Transform (x,y),scale(x,y),rotate(Angle) can be used instead.

    An example of transforming with the transform method

    Code:

    <! DOCTYPE html> <html> <head> <meta charset=utf-8> <meta name=description content=""> <meta name=viewport content="width=device-width, <canvas id="can"> </canvas> </canvas> </canvas> <script> function draw(){ var canvas = document.getElementById('can') if(canvas == null){ return false; } var context = canvas.getContext('2d'); var colors = ["red","orange","yellow","green","blue","navy","purple"]; context.lineWidth = 10; ,0,0,1,100,0 context. The transform (1) for (var I = 0; i<colors.length; I++) {context. The transform,0,0,1,0,10 (1); context.strokeStyle=colors[i]; context.beginPath(); The context. The arc (50100100, 0, Math. PI, true); context.stroke(); } } </script> </body> </html>Copy the code

    Using the setTransform method:

    context.setTransform(m11, m12, m21, m22, dx, dy)

    Examples of drawing deformed graphics:

    HTML 5 Canvas strokeStyle property

    Draw a rectangle. Please use blue pen color:

    The strokeStyle property sets or returns the color, gradient, or mode used for the stroke.

    JavaScript:

    var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.strokeStyle="#0000ff"; CTX. StrokeRect,20,150,100 (20);Copy the code

    Draw a rectangle. Using gradient strokes:

    JavaScript:

    var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); Var gradient = CTX. CreateLinearGradient,0,170,0 (0); gradient.addColorStop("0","magenta"); Gradient. AddColorStop (" 0.5 ", "blue"); Gradient. AddColorStop (" 1.0 ", "red"); // Fill with gradient ctx.strokeStyle=gradient; ctx.lineWidth=5; CTX. StrokeRect,20,150,100 (20);Copy the code

    HTML5 canvas strokeRect() method

    Draw a 150*100 pixel rectangle:

    JavaScript:

    var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); CTX. StrokeRect,20,150,100 (20);Copy the code

    Effect:

    Code:

    <! DOCTYPE html> <html> <head> <meta charset=utf-8> <meta name=description content=""> <meta name=viewport content="width=device-width, <canvas id="can"> </canvas> </canvas> </canvas> <script> function draw(){ var canvas = document.getElementById('can') if(canvas == null){ return false; } var context = canvas.getContext('2d'); context.strokeStyle = "red"; The context. StrokeRect (30,10,60,20); var rad = 45*Math.PI/180; The context. SetTransform (Math. Cos (rad), Math. Sin (rad), - Math. Sin (rad), Math. Cos (rad), 0, 0). context.strokeStyle = "blue"; The context. StrokeRect (30,10,60,20); The context. SetTransform (2.5,,0,2.5 0, 0, 0). context.strokeStyle = "green"; The context. StrokeRect (30,10,60,20); The context. SetTransform (1,0,0,1,40,80); context.strokeStyle = 'gray'; The context. StrokeRect (30,10,60,20); } </script> </body> </html>Copy the code

    In H5, you can simply use the globalCompositeOperation property of the graphics context object to determine how the graphics are composed:

    context.globalCompositeOperation=type

    The value of the type:

    1. source-overDefault value, indicating that the new graph overlays the original graph.
    2. destination-overIs used to draw a new graph under the original graph.
    3. source-inNew graphics and original graphicsinOperation, only display the overlapping part of the new graph and the original graph, the other part of the new graph and the original graph become transparent.
    4. destination-in, original graphics and new graphicsinOperation, only show the original graphics and new graphics overlap part, new graphics and other parts of the original graphics are transparent.
    5. source-outNew graphics and original graphicsoutOperation, only the new graphics and the original graphics do not overlap the part, the new graphics and other parts of the original graphics are transparent.
    6. destination-outOriginal graphics and new graphicsoutOperation, only show the original graphics and the new graphics do not overlap parts, new graphics and other parts of the original graphics are transparent.
    7. source-atopOnly the overlapping part of the new graph and the original graph without overlapping overlay are drawn, and the other parts of the new graph become transparent.
    8. destination-atopOnly the overlapped part of the original graph and other parts of the new graph are drawn, the other parts of the original graph become transparent, and the overlapped part of the new graph and the original graph are not drawn.
    9. lighterOriginal graphics and new graphics are drawn, overlap part to do color processing.
    10. xorOnly the parts of the new graph that do not overlap with the original graph are drawn, and the overlap becomes transparent.
    11. copyOnly new graphics are drawn, and the parts of the original graphics that do not overlap with the new graphics become transparent.

    Example graphic combination effects:

    Code:

    <! DOCTYPE html> <html> <head> <meta charset=utf-8> <meta name=description content=""> <meta name=viewport content="width=device-width, <canvas id="can"> </canvas> </canvas> </canvas> <script> function draw(){ var canvas = document.getElementById('can') if(canvas == null){ return false; } var context = canvas.getContext('2d'); var oprtns = new Array( "source-atop", "source-in", "source-out", "source-over", "destination-atop", "destination-in", "destination-out", "destination-over", "lighter", "copy", "xor" ); i=8; context.fillStyle = "blue"; The context. FillRect,10,60,60 (10); context.globalCompositeOperation = oprtns[i]; context.beginPath(); context.fillStyle = "red"; The context. The arc (60,60,30,0, Math. PI * 2, false); context.fill(); } </script> </body> </html>Copy the code

    Draw a shadow on the graph

    Using the properties of the graphics context object:

    1. shadowOffsetX– The lateral displacement of the shadow
    2. shadowOffsetY– The longitudinal displacement of the shadow
    3. shadowColorShadow color
    4. shadowBlurThe blurred range of shadows

    The plot

    Draw an image using the drawImage method:

    • context.drawImage(image,x,y)
    • context.drawImage(image,x,y,w,h);
    • context.drawImage(image,sx,sy,sh,dx,dy,dw,dh)

    Tiling effect

    CreatePattern method:

    context.createPattern(image,type)

    parameter describe
    image To tile the image
    type The value of the parameterno-repeat.repeat-x.repeat-y.repeat
    1. no-repeatDon’t spread
    2. repeat-xHorizontal tiling
    3. repeat-yTiling in the longitudinal direction
    4. repeatTiling in all directions

    Pixel processing

    Get the pixels in the image using the getImageData method of the graphics context object:

    var imagedata = context.getImageData(sx,sy,sw,sh)

    In HTML5: Draw text

    Rendering text

    Use the fillText method or strokeText method:

    The fillText method is used to fill a string:

    void fillText(text,x,y,[maxWidth]);

    The strokeText method draws a string in outline:

    void stroke Text(text, x, y, [maxWidth]);

    Use the measureText method to get the text width:

    metrics = context.measureText(text)

    Save and restore the state

    Use the save and restore methods in the Canvas API.

    Save the file. The principle of saving the file in Canvas API is actually the process of exporting the current drawing state to the data pointed to by a data URL address. Data URL is a base64-bit encoded URL that most browsers can recognize at present.

    Mainly used for small data that can be embedded in a web page without needing to be embedded from an external file.

    Output the drawing state to a data URL using the toDataURL method, and then reload.

    How to use toDataURL:

    canvas.toDataURL(type)

    Afterword.

    Read the article:

    The Definitive Guide to HTML5 and CSS3

    • Pull you into the technical group, long-term exchange learning…
    • Welcome to pay attention to, seriously learn the front end, do a professional technical people…

    Scan the public account to subscribe for more exciting content.