This is the 17th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

1.1 I met

Note that canvas width and height should not be set using CSS, if you use CSS style to set, it will be distorted and distorted

<canvas width="500" height="500">The current browser version does not support this. Please upgrade the browser</canvas>
Copy the code

Ie 678 does not support this

1.1.1 Basic Usage

<script>
    // Get the canvas
    var canvas = document.getElementById('myCanvas');
	// Get the context of the canvas
    var ctx = canvas.getContext('2d');
	// Set the color
    ctx.fillStyle = 'red';
	// Draw the graph
    ctx.fillRect(100.100.200.50);// The first two are the coordinates of x and y, and the last two are the width and height
</script>
Copy the code

Be sure to set the color before drawing the graphic

1.1.2 Canvas pixelation

Draw a graph with a Canvas, and once it’s drawn successfully, the canvas pixelates it. Canvas does not have the ability to get the graph from the canvas again, that is, it cannot modify the content of the canvas, which is also the reason for lightweight

To achieve the animation effect requires experience

  1. Clear the screen
  2. update
  3. Apply colours to a drawing

So it has to be redrawn

1.1.3 Canvas first animation

Achieve a box slide effect

<script>
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    ctx.fillStyle = 'skyblue';
    / / semaphore
    var left = 0;
    // Animation process
    setInterval(function() {
        / / clear screen
        ctx.clearRect(0.0.500.500);
        // The distance to the left of the canvas is increased
        left++;
        // Redraw
        ctx.fillRect(left,100.100.100);
    })
</script>
Copy the code

Each update is called a frame

1.1.4 Canvas animation realized by object-oriented thinking

Use an object-oriented approach to maintain the properties and state required by the canvas

<script>
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
	// The constructor
    function Rect(x, y, w, h, color) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.color = color;
    }
	// Add a method to the function prototype
    Rect.prototype.update = function () {
        this.x++;
    }
    Rect.prototype.render = function () {
        ctx.fillStyle = this.color;
        ctx.fillRect(this.x, this.y, this.w, this.h);
    }
	/ / instantiate
    var r1 = new Rect(100.100.50.50.'skyblue');
    var r2 = new Rect(100.200.50.50.'pink');
    setInterval(function () {
        / / clear screen
        ctx.clearRect(0.0, canvas.width, canvas.height);
        r1.update(); / / update
        r1.render(); / / redraw
        r2.update(); / / update
        r2.render(); / / redraw
    })
</script>
Copy the code

2.1 Drawing graphs

2.1.1 Filling rectangles

// Set the color
ctx.fillStyle = 'red';
// Draw the graph
ctx.fillRect(100.100.200.50); // The first two are the coordinates of x and y, and the last two are the width and height
Copy the code

2.1.2 Drawing borders

ctx.strokeStyle = 'red'; // Border color
ctx.strokeRect(300.100.100.100); // Border size
Copy the code

2.2 Drawing Paths

  1. You need to set the starting point of the path

  2. Use the draw command to draw the path

  3. A closed path

  4. Fills or draws the shape of the closed path

<script>
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    // Create a path
    ctx.beginPath();
    // Move the starting point of the position point
    ctx.moveTo(100.100);
    // Describe the path
    ctx.lineTo(200.200);
    ctx.lineTo(400.180);
    // Close the path
    ctx.closePath();
    // Draw the graph
    ctx.strokeStyle = 'red';
    ctx.stroke();Draw a line / /
</script>
Copy the code

Stroke () draws the outline of a figure with a line. StrokeRect is to draw a rectangle, so I want to pass a parameter, stroke

Fill () generates a solid figure by filling the content area of the path. fill

It is possible to draw a path without closing it (without setting closePath()), which causes self-closure (fill only).

2.3 Arc Drawing

arc(x, y, radius, startAngle, endAngle, anticlockwise)

Draw a radius arc centered on (x,y), starting with startAngle and ending with endAngle, in the direction given by AnticLockwise (clockwise by default)

<script>
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    // Create a path
    ctx.beginPath();
    // Trace the path
    ctx.arc(200.200.50.0.2 * Math.PI, false);// Default is false, clockwise
    / / path
    ctx.stroke();
</script>
Copy the code

What this means is to draw a circle clockwise with a center coordinate (200,200) of radius 50 and radians of 2PI

2.4 Case of colorful ball

Add methods to the instance object by adding methods to the prototype, so that all instantiated constructed objects are born with these methods

Implementation steps

  1. Create a small ball
  2. Give the ball a random color, a random radius
  3. Move the mouse to instantiate the ball, the new ball
  4. The ball is animated by calling the new method added to the prototype
  5. Constantly update the canvas through the timer

2.5 the transparency

ctx.globalAlpha = 0.4;
Copy the code

2.6 linear

Use lineWidth to set the thickness of the line. The value of the property must be a number. The default is 1.0

ctx.lineWidth = 10;// Set the thickness of the line
Copy the code

The lineCap property determines the property at the end of the line segment, with three values butt,round, and square

The lineJoin property determines what the two links in the graph look like round,bevel,miter(default)

SetLineDash defines a dashed line style that receives an array

ctx.setLineDash([10.20]);
Copy the code

The first parameter is the width of the dashed line, the second parameter is the distance between the two dashed lines, and so on, i.e. the alternation of the dashed lines

LineDashOffset is used to set the starting offset of the dotted line

lineDashOffset = 10;// Start of the dotted line offset light, that is, take the dotted line small space to shift how much
Copy the code

2.7 the text

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.font = '30 px song typeface';
ctx.textAlign = 'center';// The alignment is based on the x value of fillText
ctx.fillText('I am LJC'.100.100);// The text content and the location of the text
Copy the code

2.8 the gradient

Linear gradient

ctx.createLinearGradient(x0, y0, x1, y1);// The first two arguments are the start position and the last two are the end position
Copy the code
var linear = ctx.createLinearGradient(10.10.200.100);// Gradient color
linear.addColorStop(0.'red');
linear.addColorStop(0.5.'blue');
linear.addColorStop(1.'skyblue');// Gradient position and color
ctx.fillStyle = linear;/ / to color
ctx.fillRect(10.10.200.100);
Copy the code

Radial gradient

ctx.createRadialGradient(x0, y0, r0, x1, y1, r1);// Start the circle with x,y,r and end with x,y,r
Copy the code

Use the same as linear tween

2.9 the shadow

Set the text shadow effect

ctx.shadowOffsetX = 10;// How far the shadow deviates from left to right
ctx.shadowOffsetY = 10;// The distance the shadow deviates up and down
ctx.shadowBlur = 2;/ / the fuzzy value
ctx.shadowColor = 'black';// Shadow color
ctx.font = '30 px song typeface';
ctx.textAlign = 'center';
ctx.fillText('I am LJC'.100.100);// The text content and the location of the text
Copy the code

3.1 Using Pictures

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var image = new Image();// Generate the image element
image.src = 'imgs/1.jpg';// Image path
// The image must be drawn after onload, otherwise it will not be rendered
image.onload = function() {
    ctx.drawImage(image,100.100.200.200);// Load the image and the location and size of the image
}
Copy the code

Questions about parameters (not including image)

  • Two parameters, indicating the location of the drawing picture
  • Four parameters. The first two parameters indicate the position of drawing, and the last two parameters indicate the size of the picture
  • There are 8 parameters. The first two parameters describe the position of the slice, the next two are the size of the slice, the next two are the position of the cut picture, and the last two are the size of the picture
ctx.drawImage(image,0.0.200.200.0.50.90.90);
Copy the code

This means to cut a 200 * 200 slice from the image at (0,0), place it at (0,50), and scale the image to 90*90

4.1 Resource Manager

5.1 deformation

Canvas can be deformed. It is not the elements that are deformed, but the whole render area of the canvas

** Save () ** Save all states of the canvas

Restore () Restores the canvas state

Save serves as a save, kind of like when we’re playing a game, and when we want to go back to that location, we can read the file which is restore() here

Before each deformation should be archived, and then painting, so as not to affect the operation behind

5.1.1 translate translation

ctx.translate(50.50);
Copy the code

5.1.2 rotate rotating

ctx.rotate(deg)
Copy the code

5.1.3 scale zooming

The scaling here is different from that in CSS3. Two parameters need to be passed, representing the scaling ratio of x and y

ctx.scale(0.5.0.5)
Copy the code

5.1.4 Mixed writing

transform(a, b, c, d, e, f)

  • A horizontal scaling
  • B tilt offset in the vertical direction
  • C inclined offset in horizontal direction
  • D vertical scaling
  • The horizontal movement of E
  • The vertical movement of f
ctx.transform(0.5.1.1.1.1.0.5.100.100)
Copy the code

6.1 the synthesis of

This is the equivalent of the mask state, which is used to set how to gland, how to display

ctx.globalCompositeOperation = "destination-over"
Copy the code
attribute instructions
source-over This is the default, and the new graph is drawn on top of the existing graph
destination-over The new graph is drawn behind the existing content
source-in New graphics are drawn where the new graphics and existing content overlap. All other content becomes transparent.
source-out Draw new shapes only where they do not overlap with existing ones
source-atop New graphics are drawn only where they overlap with existing content
destination-in Where new graphics and existing canvases overlap, the existing content is retained. All other content becomes transparent
destination-out Where existing content and new graphics do not overlap, existing content is retained. All other content becomes transparent
destination-atop Existing content is retained only where it overlaps with the new graphic. The new graph is drawn after the content
lighter Where the shapes overlap, the color is determined by a bonus to the values of the two colors