Web front end lesson 66 – new features of H5: Canvas drawing

Time:2021-8-4

1. Canvas description

Canvas is a new label proposed by H5, which is intended to replace plug-ins similar to flash animation or games,

It can greatly reduce the page structure size and improve the page response speed.

explain:

⑴   Canvas tag is only a graphics container, providing an area where images and graphics can be drawn, which can be rendered in real time

Graphics, animation, virtual images, etc., a large number of optimization of rapid drawing;

    ⑵   useThe label habitually sets the element size inside the label and makes unsupported descriptions;

Example:

Browser does not support “canvas“!

Of course, you can also set the size attribute through CSS, and judge whether the browser supports canvas through the “if statement”.

⑶ besides providing the drawing area, the canvas tag has no other behavior functions, and all its internal contents should be through scripts

(JavaScript) finish drawing;

⑷   Use the basic template of canvas:

Your browser does not support canvas!
    
    
    //Get canvas canvas
        var canvas=document.getElementById('myCanvas');
    //Create a brush on the canvas
        var ctx=canvas.getcontext('2d');
/*// or use the if statement to determine whether the browser supports canvas
        if (canvas.getcontext){
            var ctx=canvas.getcontext('2d');
        }else {
            Canvas. InnerText = 'the browser does not support canvas!';
        }*/
    //Drawing graphics on canvas
        ctx.fillRect(10,10,60,60);

    ⑸   Most of canvas’s drawing APIs are not defined inThe element itself, but defined through the canvas

On the “drawing context environment” object obtained by the “getcontext()” method;

⑹   Canvas element only supports one kind of native graphics rendering: rectangle. All other graphics rendering needs to generate at least one path.

2. The upper screen is pixelated

On screen pixelation is an important feature of canvas, which means that once the graphics in the area are drawn, they cannot be changed, such as size, position, etc.

The effect of changing the drawn content can only be realized by clearing the content and then redrawing.

Let’s take drawing a rectangle as an example.

Related methods of drawing rectangle:

⑴   FillRect (x, y, width, height) draws a filled rectangle;

⑵   Strokerect (x, y, width, height) to draw a rectangle without filling;

⑶   Clearrect (x, y, width, height) clears the pixels in the specified rectangle;

⑷   Rect (x, y, width, height) to draw a rectangle (defining the path of the rectangle), you need to cooperate with the stroke () method to complete the drawing.

In addition, set the color of fill painting, CTX. FillStyle =’color ‘;

Code example:

Your browser does not support canvas!
    
    
    //Get canvas canvas
        var canvas=document.getElementById('myCanvas');
    //Create a brush on the canvas
        var ctx=canvas.getContext('2d');

    //Drawing graphics on canvas
        ctx.fillRect(50,50,60,60);
        ctx.strokeRect(30,30,100,100);
        ctx.clearRect(70,70,20,20);

        ctx.rect(150,150,60,60);
        ctx.stroke();       // Draw the path defined by the Rect () method

    //Through repeated clearing and drawing, the effect of image displacement is achieved.
        var position=30;
        var direction=1;
        var timer=setInterval(function () {
            if (position>=230){
                direction=-1;
            }else if (position<=10){
                direction=1;
            }
            switch (direction) {
                case -1:{
                    ctx.clearRect(position+19,position+19,102,102);
                    ctx.fillRect(position+20,position+20,60,60);
                    ctx.strokeRect(position,position,100,100);
                    ctx.clearRect(position+40,position+40,20,20);
                    position-=20;
                }
                break;
                case 1:{
                    position+=20;
                    ctx.clearRect(position-21,position-21,102,102);
                    if (position<=130) {
                        ctx.fillRect(50,50,60,60);
                        ctx.strokeRect(30,30,100,100);
                        ctx.clearRect(70,70,20,20);

                    }
                    if (position>150&&position<=210) {
                        ctx.rect(150,150,60,60);
                        ctx.stroke();
                    }
                    ctx.fillRect(position+20,position+20,60,60);
                    ctx.strokeRect(position,position,100,100);
                    ctx.clearRect(position+40,position+40,20,20);
                }
                break;
            }
        },100);

3. Route drawing

In canvas, path is the basic element of graphics. Path is a collection of points and lines formed by connecting line segments or curves with different colors, widths and lengths.

General steps for drawing a path:

(1) beginpath(), path drawing starts

⑵   Moveto (x, y) to set the coordinate position of the stroke (landing point)

(3) lineto (x, y), set the end coordinate position of the line segment

(4) strokestyle =’color ‘, set the color of stroke painting, which is black by default

(5) stroke(), execute path drawing

(6) fillStyle =’color ‘, set the internal filling color of closed path, which is black by default

(7) fill() to perform color filling

When the fill() method is used, the path without closure will be closed automatically. You can not use the closepath() function,

But the stroke () method does not automatically close the path.

(8) closepath(), the path drawing ends

Using the path start and end methods ensures independence between paths.

Code example:

Sorry, your browser does not support canvas!
    
    
        var canvas=document.getElementById('myCanvas');
        var ctx=canvas.getContext('2d');
    //Creates an unclosed path without filling
        ctx.beginPath()
        ctx.moveTo(70,80);
        ctx.lineTo(70,150);
        ctx.lineTo(120,150);
        ctx.strokeStyle='yellowgreen';
        ctx.stroke();
        ctx.closePath();
    //Creates an unclosed path for color filling
        ctx.beginPath()
        ctx.moveTo(170,80);
        ctx.lineTo(170,150);
        ctx.lineTo(220,150);
        ctx.lineTo(270,110);
        ctx.fillStyle='yellowgreen';
        ctx.fill();
        ctx.closePath();

  

4. Arc drawing

To draw an arc or circle, use the arc () method.

Syntax: ctx.arc (x, y, radius, startangle, endangle, anticlockwise);

Note: the arc () method has 6 parameters in total, which means that it takes (x, y) coordinates as the center of the circle, radius as the radius, and starts from the startangle angle

At the end of endangle, arc drawing is performed. The anticlockwise parameter is Boolean, and false indicates clockwise drawing,

True means to draw counterclockwise.

The starting and ending angles in the arc () method are in radians, not degrees!

In JS, the conversion expression of angle and radian: radius = (math. Pi / 180) * angledegrees, which is equivalent to using

Any value between “0 ~ 2” is multiplied by “math. Pi” to obtain the corresponding radian.

In addition, after setting the arc path, you can use the “stroke()” method to draw or the “fill()” method to fill.

Code example:

Your browser does not support canvas!
    
    
        var canvas = document.getElementById('canvasArc');
        var ctx = canvas.getContext('2d');
        ctx.beginPath();
        ctx.arc(200,150,60,0,0.8*Math.PI,true);
        ctx.strokeStyle='blue';
        ctx.stroke();
        ctx.closePath();

        ctx.beginPath();
        ctx.arc(200,150,60,0,0.8*Math.PI,false);
        ctx.strokeStyle='red';
        ctx.stroke();
        ctx.closePath();

        ctx.beginPath();
        ctx.arc(200,150,60,1.5*Math.PI,0.3*Math.PI,false);
        ctx.fillStyle='lightgreen';
        ctx.fill();
        ctx.closePath();

        ctx.beginPath();
        ctx.arc(200,150,60,1.5*Math.PI,0.7*Math.PI,true);
        ctx.fillStyle='orange';
        ctx.fill();
        ctx.closePath();

5. Linetype setting

⑴   Set line width

Syntax: CTX. Linewidth = value;

⑵   Set line end

Syntax: CTX. Lincap = style;

explain:

Linecap has three styles, but (default), round (round end) and square (square end)

⑶   Style line junctions

Syntax: CTX. Linejoin = style;

explain:

Linejoin has three styles: miter (default), round (circular arc) and bevel (tangent)

⑷   Set line dashed line style

Syntax: ctx.setlinedash ([segment1, segment2, segment3,…]);

explain:

The parameter of setlinedash () method is an array. The value in the array represents the length of each section of the dotted line in turn,

The values in the array will be recycled on the line bar.

Getlinedash () method is used to obtain the dotted line style of the current line, and the return value is array.

The linedashoffset() method is used to set the offset of the first section of the current line.

⑸   Code example:

var canvas=document.getElementById('canvasLineStyle');
        var ctx=canvas.getContext('2d');
        ctx.beginPath();
        ctx.moveTo(330,25);
        ctx.lineTo(399,25);
        ctx.lineTo(370,150);
        ctx.lineWidth=8;                    // Set line width
        // ctx.lineCap='round';             // Set line end style
        // ctx.lineJoin='bevel';            // Style line junctions
        ctx.setLineDash([3,2,1]);           // Set line dashed line style
        ctx.lineDashOffset=2;               // Sets the offset of the start position of the dashed line
        var lineStyle=ctx.getLineDash();    // Get dashed line style
        console.log(lineStyle);
        ctx.stroke();
        ctx.closePath();

        ctx.strokeStyle="#e20213";
        for (var i=0;i<6; i++){
            ctx.lineWidth=2+i*5;            // Set line width
            ctx.beginPath();
            ctx.moveTo(5+i*50, 25);
            ctx.lineTo(5+i*50, 150);
            ctx.stroke();
            ctx.closePath();
        }

  

6. Gradients gradient

(1) linear gradient

Syntax: CTX. Createlineargradient (x1, Y1, X2, Y2);

Note: this method has 4 parameters, (x1, Y1) represents the starting point of the gradient, and (X2, Y2) represents the end point of the gradient.

This method returns a gradient object.

⑵   Radial Gradient

Syntax: CTX. Createradiogradient (x1, Y1, R1, X2, Y2, R2);

Note: this method has 6 parameters, (x, y, R) represents a circle with (x, y) as the center and R as the radius to create a gradient area.

This method returns a gradient object.

⑶   color setting

Syntax: canvasgradient. Addcolorstop (position, color);

Note: this method has 2 parameters. The value of position is any number between “0 ~ 1”, indicating the relative position of gradient color,

The parameter color is used to set the gradient color, which can be a hexadecimal color value or an RGBA () color.

⑷   Fountain Fill

Create a gradient object, set the gradient color, and then assign the gradient object to fillStyle to paint and fill.

Code example:

 

var canvas=document.getElementById('canvasGradient');
        var ctx=canvas.getContext('2d');
    //Creates a linear gradient object.
        var linearGradient=ctx.createLinearGradient(50,50,100,100);
    //Linear gradient object color settings.
        linearGradient.addColorStop(0,'red');
        linearGradient.addColorStop(0.5,'yellow');
        linearGradient.addColorStop(1,'yellowgreen');
    //Linear gradient painting.
        ctx.beginPath();
        ctx.fillStyle=linearGradient;
        ctx.fillRect(10,10,150,150);
        ctx.closePath();

    //Creates a radial gradient with an outer circle containing an inner circle.
        var radialGradient=ctx.createRadialGradient(300,80,10,270,80,80);
        radialGradient.addColorStop(0,'red');
        radialGradient.addColorStop(0.5,'yellow');
        radialGradient.addColorStop(1,'yellowgreen');
        ctx.beginPath();
        ctx.fillStyle=radialGradient;
        ctx.fillRect(200,10,150,150);
        ctx.fill();
        ctx.closePath();

        //Creates a radial gradient, the outer circle does not contain the inner circle.
        var radialGradient=ctx.createRadialGradient(500,80,30,600,80,60);
        radialGradient.addColorStop(0,'red');
        radialGradient.addColorStop(0.5,'yellow');
        radialGradient.addColorStop(1,'yellowgreen');
        ctx.beginPath();
        ctx.fillStyle=radialGradient;
        ctx.fillRect(360,10,300,150);
        ctx.fill();
        ctx.closePath();

  

Recommended Today

OC basis

IOS development interview essential skills chart.png What are objects and what are the objects in OC? An object is an instance of a class; Is an instance created through a class, which is generally called an instance object; Common objects in OC include instance objects, class objects, and metaclass objects; What is a class? What […]