1. What is Canvas

Definition 1-1

Canvas is translated as canvas in English. As a label of HTML5,canvas’s main function is painting. That is to say, canvas can be used to draw images on web pages with javasccript, and each pixel can be precisely controlled.

1-2 purposes

(1) animation, game development (2) visualization data, such as Echarts charts, etc. (3) banner ads

2. The canvas

Canvas is a common HTML closing tag. You can set width and height attributes, in unit of PX, and the default value is 300*150 if not set. Canvas is supported only when Internet Explorer 9 is above, and other Chrome, FF and Apple browsers all support it.

<canvas id="cavasEle"> Your browser does not support canvas, please upgrade your browser. Browsers do not support this line of text </canvas>Copy the code

Canvas has a variety of ways to draw paths, rectangles, circles, characters and add images. There are the following key concepts:

(1) the Context:

Canvas context, drawing environment. Context is the javascript entry to the Canvas, obtained using canvas.getContext(‘2d’).

let canvas = document.getElementById('cavasEle'); 
canvas.width = 1200;
canvas.height = 900;
let ctx = canvas.getContext('2d'); 
Copy the code
(2) Coordinate system:

Canvas coordinates, starting at the top left corner, 0,0. X goes up to the right, y goes down

(3) Draw a straight line

Just as we draw a straight line on a piece of paper, first place the stroke at the beginning of the drawing and then start drawing until the end of the line. The code is shown as follows:

// Simple lines
// Set the starting and ending width color of the line state
ctx.moveTo(100.100);
ctx.lineTo(100.700);
ctx.lineWidth = 3;

// Start drawing strokes to draw lines
ctx.strokeStyle = "red";
ctx.stroke();

// Lines connect to form shapes
ctx.moveTo(200.200);
ctx.lineTo(700.700);
ctx.lineTo(200.700);
ctx.lineTo(200.200);

// Start drawing strokes to draw lines
ctx.strokeStyle = "rgb(0,0,0)";
ctx.stroke(); / / stroke
Copy the code
(4) Path opening and closing

In the above code operation, we draw a red line and a black triangle, but the drawing result is two black. This is because canvas is state-based drawing. The next drawing will inherit the previous drawing state before the last drawing state ends. We need the path open and close tool to isolate the two different operations.

Start path: ctx.beginPath(); Each time this method is executed, it means to redraw a path, and the previous drawing ink can be separated from the style setting and management.

ClosePath: ctx.closepath ();

ctx.beginPath();
ctx.moveTo(100.100);
ctx.lineTo(100.700);
ctx.closePath();

// Start drawing strokes to draw lines
ctx.lineWidth = 3;
ctx.strokeStyle = "red";
ctx.stroke();

// Lines connect to form shapes
ctx.beginPath();
ctx.moveTo(200.200);
ctx.lineTo(700.700);
ctx.lineTo(200.700);
ctx.lineTo(200.200);
ctx.closePath();

// Start drawing strokes to draw lines
ctx.strokeStyle = "rgb(0,0,0)";
ctx.stroke();
ctx.fillStyle = "red";
ctx.fill()
Copy the code

Summary of key points code:

/ / line
context.moveTo()  // Move the brush position
context.lineTo()
context.beginPath()
context.closePath()
// Style Settings
context.lineWidth / / line width
context.strokeStyle / / stroke
context.fillStyle  / / fill
/ / to draw
context.stroke()
context.fill()
Copy the code
(5) Tangram drawing example

Before drawing, we should first know the coordinate position of each shape of the tangram, as shown in the figure:

The code is as follows:

let tangram = [
    {p: [{x:0.y:0}, {x:800.y:0}, {x:400.y:400}].color:"#caff67"},
    {p: [{x:0.y:0}, {x:400.y:400}, {x:0.y:800}].color:"#67becf"},
    {p: [{x:800.y:0}, {x:800.y:400}, {x:600.y:600}, {x:600.y:200}].color:"#ef3d61"},
    {p: [{x:600.y:200}, {x:600.y:600}, {x:400.y:400}].color:"#f9f51a"},
    {p: [{x:400.y:400}, {x:600.y:600}, {x:400.y:800}, {x:200.y:600}].color:"#a594c0"},
    {p: [{x:200.y:600}, {x:400.y:800}, {x:0.y:800}].color:"#fa8ecc"},
    {p: [{x:800.y:400}, {x:800.y:800}, {x:400.y:800}].color:"#f6ca29"},];let canvas = document.getElementById('cavasEle'); 
canvas.width = 1200;
canvas.height = 900;
let ctx = canvas.getContext('2d');
function drawTangram () {
    for(let i=0; i<tangram.length; i++){
        let piece = tangram[i];
        ctx.beginPath();
        ctx.moveTo(piece.p[0].x, piece.p[0].y);
        for(let j=1; j<piece.p.length; j++){
            ctx.lineTo(piece.p[j].x, piece.p[j].y);
        }
        ctx.closePath();
        ctx.fillStyle = piece.color;
        ctx.stroke();
        ctx.fill()
    }
}
drawTangram();
Copy the code

The effect is shown below:

(6) Draw shape text
6-1 Draw circles and arcs
context.arc(centerx,                    // Center x coordinates
            centery,                    // The center of the circle is y
            radius,                     / / circle radius
            startingAngle,              // Start Angle
            endingAngle,                // End Angle
            anticlockwise = false);     // Clockwise :false counterclockwise true

// demo
ctx.beginPath();
ctx.lineWidth = 3;
ctx.strokeStyle = "red";
ctx.arc(50.50.20.0.1.5*Math.PI);
ctx.stroke();

ctxCircle.beginPath();
ctxCircle.arc(90.50.20.0.1.5*Math.PI, true);
ctx.strokeStyle = "black";
ctxCircle.stroke();
Copy the code

6-2 Draw a rectangle
Rect (x, // draw the starting x coordinate y, // draw the starting y coordinate width, // rectangle width height); // rectangle height // x, y is the coordinates of the top left corner of the rectangle context.stroke(); StrokeRect (x, y, width, height) // (3) fillRect(x, y, width, height) ClearRect (x, y, width, hegiht);Copy the code
6-3 Draw text

The text style Settings are the same as the CSS

context.moveTo(300, 300); context.fillStyle = 'purple'; // Set the fill color to purple context.font = '20px "Microsoft Yahei"; TextBaseline = 'bottom'; Context. textAlign = 'left'; Context. StrokeText ("hello", 360, 250); // Draw text on the canvas (no padding) context.fillText(' Hello world', 660, 250); // Fill the text let text1 = context.measureText('hello') // Return an object containing the specified text width console.log(text1) let text2 = context.measureText('hello world') console.log(text2)Copy the code
(7) Animation drawing of ball movement

In order to create a ball motion animation effect with canvas, it is preferred to know the motion track of the ball, which requires the physics knowledge we have learned before. A brief diagram of ball motion is as follows:

The code is as follows:

// data:
let runBallConfig = {
        ballRadius: 20.startX: 30.startY: 30.vx: 5.vy: 0.g: 2,}// js:
let canvasBall = this.$refs.canvasBall;
canvasBall.width = 1200;
canvasBall.height = 400;
ctxBall = canvasBall.getContext("2d");
drawRunBall(runBallConfig.startX, runBallConfig.startY);
setInterval(() = >{
    updateBall();
},50)

updateBall(){
    runBallConfig.startX += runBallConfig.vx
    runBallConfig.startY += runBallConfig.vy
    runBallConfig.vy += runBallConfig.g
    drawRunBall(runBallConfig.startX, runBallConfig.startY);
    // Critical judgment
    if(runBallConfig.startY >= 400 - runBallConfig.ballRadius){
        runBallConfig.startY = 400 - runBallConfig.ballRadius;  / / to the ground
        runBallConfig.vy = - (runBallConfig.vy) * 0.5;   // Friction coefficient 0.5}},drawRunBall(x, y){
    ctxBall.clearRect(0.0.1200.400);
    ctxBall.beginPath();
    ctxBall.lineWidth = 3;
    ctxBall.strokeStyle = "red";
    ctxBall.arc(x, y, runBallConfig.ballRadius, 0.2*Math.PI);
    ctxBall.stroke();
    ctxBall.fillStyle = "red";
    ctxBall.fill()
},
Copy the code
(8) Draw pictures
// Picture drawing
context.drawImage(img, x, y, width, height);
//img is the DOM object to draw the image, and x and y are the coordinates of the upper left corner of the drawing.
//width, height Draws the image's width and height
// Image clipping
context.drawImage(img, sx, sy, swidth, sheight, x, y, width, height);
// sx, sy clipped xy coordinates
// swidth, sheight clipped image xy
Copy the code
(9) Line chart Demo and pie chart Demo

Git address: github.com/aicai0/test…

If you have any questions, welcome to discuss, if you are satisfied, please manually click “like”, thank you! 🙏

For more postures, please pay attention!!