Canvas series starting at 0

Canvas series 1 – Canvas canvas

Canvas series 2 – Text and images from 0

Canvas series 3 – pixel level manipulation of images from 0

Canvas series 4 – Motion animation drawing from 0

Canvas series 5 – Animation from 0

Canvas Series 6 from 0 – Composition and clipping

Starting from 0, the final chapter of Canvas series — create cool particle effects

What is a canvas

Canvas is a newly added element of HTML5. It can draw graphics through javascript scripts. It can be used for animation, game graphics, data visualization, image editing, and real-time video processing.

To put it simply, Canvas provides a canvas. Call the getContext attribute (which can be 2D or WebGL 3D) to define the brush, define the drawing method of the graph by setting the fill or stroke attribute of the image, and complete the drawing of the graph once. Each drawing uses the drawn path as a drawing unit

Each drawing process can be summarized as the following steps

 // Get the canvas
const  canvas=document.querySelector('#canvas');
// Define the brush
const ctx=canvas.getContext('2d');
// Set the color of the brush
ctx.fillStyle='red';
// Start drawing a path once
ctx.beginPath();
// Set the starting coordinates
ctx.moveTo(x,y);
// Define the shape of the drawing graphArc (x,y,r, starting radian, ending radian, direction);// Define the arc
// Render path
ctx.fill()
Copy the code

How to use the canvas

Canvas is a process of drawing. When you write JS code, it is a process of drawing. Canvas API provides a tool for drawing

Canvas (Paper and pen ready)

  • Canvas The coordinate system and grid of a canvas
    • The coordinate system is two dimensions, x/y
    • The bigger the X-axis goes to the right, the bigger the Y-axis goes down
    • Pixels are the smallest cell (raster), each pixel has RGBA data, and the number of pixels is equal to the length * width of the canvas

  • Canvas Size Settings for the canvas
    • Canvas length and width can be interline styles
    • Can through the canvas. Width/canvas. Height definition
    • Limit size control within 4000
    • Do not use CSS style Settings, it will cause graphical distortion
<canvas id="canvas" width="700" height="800"></canvas>

const  canvas=document.querySelector('#canvas');
canvas.width=300;
canvas.height=150;
Copy the code
  • Canvas brushes
    • 2 d brush
    • 3 d brush
/ / 2 d brush
const  ctx=canvas.getContext('2d');
/ / 3 d brush
const  ctx=canvas.getContext('webgl');
Copy the code

Canvas drawing graphics

Basic graphics

A straight line

  • lineTo(x,y)
  /* lineTo(x,y); * /
  ctx.beginPath();
  ctx.moveTo(50.50);
  ctx.lineTo(400.50);
  ctx.lineTo(400.300);
  ctx.closePath();
  ctx.stroke();
Copy the code

The circular arc

  • Arc (x,y, radius, start radian, end radian, direction)

    Direction: true clockwise, false counterclockwise

  ctx.beginPath();
  ctx.arc(300.300.100.0.Math.PI*3/2.true);/ / clockwise
  ctx.stroke();

  ctx.moveTo(700.300);
  ctx.arc(600.300.100.0.Math.PI*3/2.false);
  ctx.stroke();
Copy the code

The tangent arc

  • ArcTo (x1, y1, x2, y2, radius)

    The coordinates are described as follows

ctx.beginPath();
ctx.moveTo(50.50);
ctx.arcTo(400.50.400.300.100);
ctx.stroke();
Copy the code

Quadratic Bessel curve

Bezier curve principle

  • quadraticCurveTo(cpx1,cpy1,x,y)

    • Cpx1 / CPY1 represents the control point, and x/y represents the end point

    The drawing process is as follows (p1 control point, P2 end point) :

    • The continuous point Q0 from P0 to P1 describes a line segment.

    • The continuous point Q1 from P1 to P2 describes a line segment.

    • Describe a quadratic Bessel curve from the continuous point B(t) Q0 to Q1.

ctx.beginPath();
ctx.moveTo(50.50);
ctx.quadraticCurveTo(400.50.400.300);
ctx.stroke();
Copy the code

Cubic Bezier curves

  • bezierCurverTo(cpx1,cpy1,cpx2,cpy2,x,y)

    • Cpx1 / CPY1 CPX2 / cpY2 indicates the control point, and x/y indicates the end point

ctx.beginPath();
ctx.moveTo(50.50);
ctx.bezierCurveTo(
    400.50.400.300.800.300
)
ctx.stroke();
Copy the code

rectangular

  • Basic rectangular

    rect(x,y,w,h)

    • Rectangles do not need to specify a starting point

    ctx.beginPath();
    ctx.rect(50.50.400.200);
    ctx.stroke();
    ctx.fill();
    Copy the code
  • Fill the rectangle

    fillRect(x,y,w,h)

  • Stroke rectangle

    strokeRect(x,y,w,h)

  • Clean rectangle (eraser)

    ctx.clearRect(x,y,w,h);

Extension path

From the drawing process of each graph, we can find that there are the following rules in the drawing process of each graph:

  1. First, create the drawing starting point.
  2. Then, use the Draw command to set up the graph.
  3. Finally, render the graphics by stroke or filling the path area.

The above three processes are actually a path creation process

The basic element of the graph is the path. A path is a collection of points of different shapes connected by line segments or curves of different colors and widths. A path, or even a subpath, is closed.

The API for paths is as follows

  • beginPath()

    Create a new path set. After it is generated, the graph drawing command is directed to the path set to generate the path.

    The current path is empty, that is, after beginPath() is called, or when canvas is first built, the first path construction command is usually treated as moveTo (), no matter what it actually is. For this reason, you almost always specify your starting location after setting the path.

  • closePath()

    After the path is closed, the graph drawing command points back to the context.

  • stroke()

    Use lines to draw the outline of a graph.

  • fill()

    Generates solid graphics by filling the content area of the path.

    When you call fill(), all shapes that are not closed will be closed automatically, so you don’t need to call closePath(). But stroke() is not closed automatically.

Path and subpath

  • Path:
    • A path is a collection of subpaths
    • A context object has only one path at a time. To draw a new path, empty the current path.
    • The beginPath() method empties the current path, that is, restores the path to its default state so that subsequent paths are not affected by previous paths.
  • subpath
    • A subpath is a continuous line with a single starting point
    • MoveTo (x,y) is a way to set the starting point of a path and also to create a new subpath
    • The first sliver in a path does not need a starting point; its starting point defaults to the first point in the child path

A diagram of the two

BeginPath Starts a path
ctx.beginPath();
// subpath 1
ctx.moveTo(190.100);
ctx.arc(100.100.90.0.Math.PI*2);

ctx.beginPath();// Add before and after the effect as shown in figure

// subpath 2
ctx.moveTo(400.300);
ctx.arc(300.300.100.0.Math.PI*2);
ctx.stroke();
Copy the code
No beginPath () Have the beginPath ()

Graphic coloring and Stroke (Coloring and Stroke)

Note: coloring or stroke is actually done before drawing

Graph coloring

The coloring is divided into two parts: fillStyle (inner fill area) and stokeStyle (stroke area).

FillStyle (graphic fill area)

Ctx. fillStyle is a property of the Canvas 2D API that describes colors and styles internally. The default value is #000 (black).

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

ctx.fillStyle = "blue";
ctx.fillRect(10.10.100.100);
Copy the code

FillStyle uses a for loop example

var ctx = document.getElementById('canvas').getContext('2d');
for (var i=0; i<6; i++){for (var j=0; j<6; j++){ ctx.fillStyle ='rgb(' + Math.floor(255-42.5*i) + ', ' +
                     Math.floor(255-42.5*j) + ', 0) ';
    ctx.fillRect(j*25,i*25.25.25); }}Copy the code

StokeStyle (Stroke area)

Ctx. stokenStyle is the Canvas 2D API property that describes the color or style of the brush. The default is #000 (black).

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

ctx.strokeStyle = "blue";
ctx.strokeRect(10.10.100.100);
Copy the code

StokeStyle uses an example of a for loop

var ctx = document.getElementById('canvas').getContext('2d');
for (var i=0; i<6; i++){for (var j=0; j<6; j++){ ctx.strokeStyle ='rgb(0,' + Math.floor(255-42.5*i) + ', ' + 
                      Math.floor(255-42.5*j) + ') ';
    ctx.beginPath();
    ctx.arc(12.5+j*25.12.5+i*25.10.0.Math.PI*2.true); ctx.stroke(); }}Copy the code

Coloring style

There are three ways to color a graph

  • Pure color
  • The gradient
  • texture

The corresponding code is

ctx.fillStyle = color; ctx.fillStyle = gradient; ctx.fillStyle = pattern; ctx.strokeStyle = color; ctx.strokeStyle = gradient; ctx.strokeStyle = pattern; Color DOMString A string that can be converted to a CSS <color> value. Gradient CanvasGradient object (linear gradient or radioactive gradient). Pattern CanvasPattern object (repeatable picture).Copy the code
  • Pure color
ctx.fillStyle='blue';
ctx.fillStyle='#00acec';
ctx.fillStyle='RGB (255,0,255)';
ctx.fillStyle='RGBA (0,0,255,0.5)';
Copy the code
  • The gradient

    Gradients are more complex to set than solid colors. You need to set the starting and ending coordinates and the starting color, and you can also add points and colors in the middle

    Gradient can be divided into linear gradient and radial gradient

Linear gradient Radial gradient

The specific Settings are as follows

  1. Set the gradient object (start and end coordinates)
// Linear gradient
const gr = ctx.createLinearGradient(x1, y1, x2, y2)
// Radial gradient
const gr = ctx.createRadialGradient(x1, y1, r1, x2, y2, r2)

x1,y1: starting coordinate R1: starting coordinate radius x2,y2: terminal coordinate R2: radius of terminal coordinateCopy the code
  1. Define the color of each coordinate
gr.addColorStop(position, color)

position: Position, value0-1.0Is the starting point,1Color: solid colorCopy the code
  1. Assign a value to the style
ctx.fillStyle = gr;
ctx.stokeStyle = gr;
Copy the code

Linear gradient demo

  const canvas=document.getElementById('canvas');
  // Canvas fills the window
  canvas.width=window.innerWidth;
  canvas.height=window.innerHeight;

  // brush - context object
  const ctx=canvas.getContext('2d');

  /* 1. Create a gradient object and define the area of the gradient */
  const gr=ctx.createLinearGradient(50.50.450.450);

  /* 2. Add the color node */ for the gradient
  gr.addColorStop(0.'red');
  gr.addColorStop(0.5.'yellow');
  gr.addColorStop(1.'#00acec');

  /* 3. Assign the style */
  ctx.fillStyle=gr;

  /* 4
  ctx.fillRect(50.50.400.400);
Copy the code

Radial gradient demo

  const canvas=document.getElementById('canvas');
  // Canvas fills the window
  canvas.width=window.innerWidth;
  canvas.height=window.innerHeight;

  // brush - context object
  const ctx=canvas.getContext('2d');

  /* 1. Create a gradient object and define the area of the gradient */
  const gr=ctx.createRadialGradient(
      300.300.20.400.300.200
  )

  /* 2. Add the color node */ for the gradient
  gr.addColorStop(0.'red');
  gr.addColorStop(0.5.'yellow');
  gr.addColorStop(1.'#00acec');

  /* 3. Assign the style */
  ctx.fillStyle=gr;

  /* 4
  ctx.fillRect(50.50.600.600);
Copy the code

  • texture

A texture is an image filled repeatedly and is set up in a similar way to the gradient step

  1. Setting texture Objects

const pt = ctx.createPattern(image,"repeat|repeat-x|repeat-y|no-repeat");

  1. Assign a value to the style

ctx.fillStyle=pt

Texture demo

  const img=new Image();
  img.src='./images/floor.jpg';
  img.onload=function(){
      const pt=ctx.createPattern(img,'repeat');
      ctx.fillStyle=pt;
      ctx.fillRect(0.0,canvas.width,canvas.height);
  }
Copy the code

Graphics stroke

  • strokeStyle/lineWidth

    Stroke color and width

    // This has been mentioned above
    ctx.strokeStyle = color 
    
    ctx.lineWidth = value
    value: A number describing the width of a line segment.0, negative,InfinityNaNWill be ignoredCopy the code
  • lineCap

    Stroke endpoint style

     ctx.save();
     ctx.lineCap='butt/round/square';
     ctx.beginPath();
     ctx.moveTo(50.50);
     ctx.lineTo(400.50); ctx.stroke(); ctx.restore(); LineCap Stroke endpoint style * butt has no endpoint, default * round endpoint * square endpointCopy the code
butt round square
  • lineJoin

    The corner type

      ctx.save();
      ctx.lineJoin='miter/round/bevel';
      ctx.beginPath();
      ctx.moveTo(50.50);
      ctx.lineTo(400.50);
      ctx.lineTo(200.150); ctx.stroke(); ctx.restore(); LineJoin Corner type * miter * round * bevelCopy the code
    miter round bevel
  • setLineDash

Segments a CTX. SetLineDash (segments)ArrayThe array. A group of numbers describing the length of alternately drawn line segments and spacing (units of coordinate space). The data in the array simply represents the length of each dotted line, regardless of alternate dotted linesCopy the code

CTX. SetLineDash (60 living [])

60,90,120 CTX. SetLineDash ([])

  • projection

Location: shadowOffsetX, shadowOffsetY

Blur: “shadowBlur”

Color: shadowColor

    ctx.shadowColor='# 000';
    ctx.shadowOffsetY=30;
    ctx.shadowOffsetX=30;
    ctx.shadowBlur=30;
    ctx.beginPath();
    ctx.arc(300.200.100.0.Math.PI*2);
    ctx.fillStyle='#93abff';
    ctx.fill();
Copy the code