Canvas from the beginning to the pig

Time:2021-6-8

Pay attention to the official account of “kite holders”, reply to “information” to get 500G information (all “arms”), and professional exchange groups. Ha ha)

Through this article, you will understand the introduction of canvas and its more commonly used methods, and use canvas to achieve a piggy head.

1、 Introduction to canvas

1.1 what is canvas

Canvas (canvas) is a new tag added in HTML5, which is used to generate images in real time on Web pages. It can manipulate image content. It is a bitmap that can be operated by JavaScript.

1.2 coordinate system of canvas

The coordinate system of canvas is shown in the figure below, which has the following characteristics:

  • The positive direction of x-axis is right and the positive direction of y-axis is down
  • The origin of the canvas is in the upper left corner
  • Abscissa and ordinate are in pixels
  • The minimum cell of each axis is one pixel (grid)

Canvas from the beginning to the pig

1.3 drawing process of canvas

  1. Create a < canvas > < / Canvas > tag
  2. Get the DOM object corresponding to the canvas element, which is a canvas object
  3. Call the getcontext () method of the canvas object, which returns a canvasrenderingcontext2d object, which can draw graphics
  4. Call the drawing method of canvasrenderingcontext2d object

1.4 application fields of canvas

Canvas is a magic thing that can be applied in many fields. Let’s talk about it together.

  1. Games: canvas is more three-dimensional and sophisticated than flash in web-based image display, and canvas games are better in fluency and cross platform, such as this25 canvas games
  2. Visual Library: ecart
  3. Banner advertising: canvas is very suitable to achieve dynamic advertising effect
  4. Graphic editor: subsequent Photoshop can be realized 100% based on Web
  5. Wechat reading and Tencent documents are all implemented through canvas

2、 Basic functions

Through the first chapter, we have a preliminary understanding of canvas. This chapter will evolve according to the idea of a person drawing a painting, and gradually understand the basic functions of canvas, so as to better use it to achieve some cool effects.

2.1 selection of coordinate system

When you want to draw a picture, you must first determine the coordinate system. Only after you have selected the coordinate system can you move the pen easily. In canvas, the default coordinate system is in the upper left corner (the positive direction of X axis is right, and the positive direction of Y axis is down). But sometimes you need to change the coordinate system to achieve the desired effect more conveniently. At this time, you need to change the coordinate system, Canvas provides the following ways to transform coordinate systems:

  1. Translate (DX, Dy): translation coordinate system. It is equivalent to translating the original coordinate origin at (0,0) position to (DX, Dy) point.
  2. Rotate (angle): rotate the coordinate system. This method controls the coordinate system to rotate angle radian clockwise.
  3. Scale (SX, SY): scale the coordinate system. This method controls the coordinate system to scale SX horizontally and sy vertically.
  4. Transform (a, B, C, D, e, f): allows scaling, rotating, moving and tilting the current environment coordinate system, where a represents horizontal scaling, B represents horizontal skewing, C represents vertical skewing, D represents vertical scaling, e represents horizontal moving and f represents vertical moving.

Canvas from the beginning to the pig

function main() {
    const canvas = document.getElementById('canvasId');
    const ctx = canvas.getContext('2d');
    ctx.lineWidth = 4;
    //Default
    ctx.save();
    ctx.strokeStyle = '#F00';
    drawCoordiante(ctx);
    ctx.restore();

    //Translation
    ctx.save();
    ctx.translate(150, 150);
    ctx.strokeStyle = '#0F0';
    drawCoordiante(ctx);
    ctx.restore();

    //Rotation
    ctx.save();
    ctx.translate(300, 300);
    ctx.rotate(-Math.PI / 2);
    ctx.strokeStyle = '#00F';
    drawCoordiante(ctx);
    ctx.restore();

    //Zoom
    ctx.save();
    ctx.translate(400, 400);
    ctx.rotate(-Math.PI / 2);
    ctx.scale(0.5, 0.5);
    ctx.strokeStyle = '#000';
    drawCoordiante(ctx);
    ctx.restore();
}

function drawCoordiante(ctx) {
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(120, 0);
    ctx.moveTo(0, 0);
    ctx.lineTo(0, 80);
    ctx.closePath();
    ctx.stroke();
}

main();

2.2 graphic drawing

After the coordinate system is selected, we will start to write a masterpiece. What is canvas allowed to draw?

  1. straight line
function drawLine(ctx, startX, startY, endX, endY) {
    ctx.moveTo(startX, startY);
    ctx.lineTo(endX, endY);
    ctx.stroke();
}
  1. arc
function drawCircle(ctx, x, y, R, startAngle, endAngle) {
    ctx.arc(x, y, R, startAngle, endAngle);
    ctx.stroke();
}
  1. curve
//Bezier curve
function drawBezierCurve(ctx, cpX1, cpY1, cpX, cpY2, endX, endY) {
    ctx.bezierCurveTo(cpX1, cpY1, cpX, cpY2, endX, endY);
    ctx.stroke();
}
//Conic
function drawQuadraticCurve(ctx, cpX, cpY, endX, endY) {
    ctx.quadraticCurveTo(cpX, cpY, endX, endY);
    ctx.stroke();
}
  1. rectangle
//Fill rectangle
function drawFillRect(ctx, x, y, width, height) {
    ctx.fillRect(x, y, width, height);
}
//Border rectangle
function drawStrokeRect(ctx, x, y, width, height) {
    ctx.strokeRect( x, y, width, height);
}
  1. character string
//Fill string
function drawFillText(ctx, text, x, y) {
    ctx.fillText(text, x, y);
}
//Border string
function drawStrokeText(ctx, text, x, y) {
    ctx.strokeText(text, x, y);
}
  1. Complex graphics drawing — path
//Drawing by path
function drawFigureByPath(ctx) {
    ctx.beginPath();
    ctx.moveTo(100, 400);
    ctx.lineTo(200, 450);
    ctx.lineTo(150, 480);
    ctx.closePath();
    ctx.fill();
}

Canvas from the beginning to the pig

function main() {
    const canvas = document.getElementById('canvasId');
    const ctx = canvas.getContext('2d');
    ctx.lineWidth = 2;
    ctx.strokeStyle = '#F00';
    ctx.fillStyle = '#F00';
    CTX. Font ='normal 50px Song Ti ';
    drawLine(ctx, 50, 10, 150, 10);
    ctx.moveTo(150, 100);
    drawCircle(ctx, 100, 100, 50, 0, Math.PI);
    ctx.moveTo(300, 100);
    drawCircle(ctx, 250, 100, 50, 0, Math.PI * 2);
    ctx.moveTo(350, 150);
    drawBezierCurve(ctx, 200, 200, 450, 250, 300, 300);
    ctx.moveTo(50, 250);
    drawQuadraticCurve(ctx, 50, 400, 80, 400);
    drawFillRect(ctx, 100, 300, 100, 50);
    drawStrokeRect(ctx, 300, 300, 100, 50);
    drawFillText(ctx, 'I', 100, 400);
    drawStrokeText(ctx, 'I', 300, 400);
    drawFigureByPath(ctx);
}

2.3 filling style

When using canvas to draw graphics, it is necessary to add some pigment. The corresponding pigment can be set by setting fillStyle attribute. There are four main pigment values: pure color, linear gradient color, radial gradient color and bitmap.

  1. Pure color
function useColorFill(ctx) {
    ctx.save();
    ctx.fillStyle = '#F00';
    ctx.fillRect(10, 10, 100, 100);
    ctx.restore();
}
  1. Linear gradient color
function useLinearGradientFill(ctx) {
    ctx.save();
    const lg = ctx.createLinearGradient(110, 10, 210, 10);
    lg.addColorStop(0.2, '#F00');
    lg.addColorStop(0.5, '#0F0');
    lg.addColorStop(0.9, '#00F');
    ctx.fillStyle = lg;
    ctx.fillRect(120, 10, 100, 100);
    ctx.restore();
}
  1. Radial gradient color
function useRadialGradientFill(ctx) {
    ctx.save();
    const lg = ctx.createRadialGradient(260, 60, 10, 260, 60, 60);
    lg.addColorStop(0.2, '#F00');
    lg.addColorStop(0.5, '#0F0');
    lg.addColorStop(0.9, '#00F');
    ctx.fillStyle = lg;
    ctx.fillRect(230, 10, 100, 100);
    ctx.restore();
}
  1. Bitmap fills
function useImageFill(ctx) {
    ctx.save();
    const image = new Image();
    image.src = 'https://dss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=442547030,98631113&fm=58';
    image.onload = function () {
        //Create bitmap fill
        const imgPattern = ctx.createPattern(image, 'repeat');
        ctx.fillStyle = imgPattern;
        ctx.fillRect(340, 10, 100, 100);
        ctx.restore();
    }
}

Canvas from the beginning to the pig

2.4 temporary preservation

When drawing a beautiful woman with a paintbrush, you suddenly get inspiration and need to draw another handsome man. At this time, you don’t want to give up the beautiful woman, so you need to temporarily save the paint, coordinates and other states of the current painting of the beautiful woman. After the painting of the handsome man, you need to restore the state to draw the beautiful woman. In canvas, you can use save() and restore() methods. After calling save() method, you can put the setting of this moment into a temporary stack, and then you can safely modify the context. When you need to draw the previous context, you can call restore() method.
Canvas from the beginning to the pig

//Draw from left to right in turn (fill with new style in the middle and restore to original style in the last)
function main() {
    const canvas = document.getElementById('canvasId');
    const ctx = canvas.getContext('2d');
    ctx.fillStyle = '#F00';
    ctx.fillRect(10, 10, 100, 100);
    ctx.save();
    ctx.fillStyle = '#0F0';
    ctx.fillRect(150, 10, 100, 100);
    ctx.restore();
    ctx.fillRect(290, 10, 100, 100);
}

2.5 introduction of external images

Sometimes it is necessary to introduce an external image, then process the external image at the pixel level, and finally save it.

  1. Draw image: DrawImage
  2. Get image data: getiamgedata
  3. Refill the modified data into canvas: putimagedata
  4. Output bitmap: todataurl

Canvas from the beginning to the pig

function main() {
    const canvas = document.getElementById('canvasId');
    const ctx = canvas.getContext('2d');
    const image = document.getElementById('image');
    //Draw an image
    ctx.drawImage(image, 0, 0);
    //Get image data
    const imageData = ctx.getImageData(0, 0, image.width, image.height);
    const data = imageData.data;
    for (let i = 0, len = data.length; i < len; i += 4) {
        const red = data[i];
        const green = data[i + 1];
        const blue = data[i + 2];

        const average = Math.floor((red + green + blue) / 3);

        data[i] = average;
        data[i + 1] = average;
        data[i + 2] = average;
    }

    imageData.data = data;
    ctx.putImageData(imageData, 0, 0);
    document.getElementById('result').src = canvas.toDataURL('image/png');
}

3、 Pig head actual combat

After learning so much, let’s use canvas to draw a pig’s head. After all, every programmer must have a fat pig beside him, hehe.
Canvas from the beginning to the pig

function main() {
    const canvas = document.getElementById('canvasId');
    const ctx = canvas.getContext('2d');
    ctx.lineWidth = 4;
    ctx.strokeStyle = '#000';
    ctx.fillStyle = '#ffd8e1';
    ctx.translate(260, 20);
    drawPigEar(ctx);
    ctx.save();
    ctx.rotate(Math.PI / 2);
    drawPigEar(ctx);
    ctx.restore();
    drawPigFace(ctx);
    ctx.save();
    ctx.translate(-100, -100);
    drawPigEye(ctx);
    ctx.restore();
    ctx.save();
    ctx.translate(100, -100);
    drawPigEye(ctx);
    ctx.restore();
    ctx.save();
    ctx.translate(0, 60);
    drawPigNose(ctx);
    ctx.restore();
}

function drawPigEar(ctx) {
    ctx.save();
    ctx.beginPath();
    ctx.arc(-250, 0, 250, 0, -Math.PI / 2, true);
    ctx.arc(0, -250, 250, -Math.PI, Math.PI / 2, true);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
    ctx.restore();
}

function drawPigFace(ctx) {
    ctx.save();
    ctx.beginPath();
    ctx.arc(0, 0, 250, 0, Math.PI * 2);
    ctx.fill();
    ctx.stroke();
    ctx.closePath();
    ctx.restore();
}

function drawPigEye(ctx) {
    ctx.save();
    ctx.fillStyle = '#000';
    ctx.beginPath();
    ctx.arc(0, 0, 20, 0, Math.PI * 2);
    ctx.closePath();
    ctx.fill();
    ctx.restore();
}

function drawPigNose(ctx) {
    ctx.save();
    ctx.fillStyle = '#fca7aa';
    ctx.beginPath();
    ctx.ellipse(0, 0, 150, 100, 0, 0, Math.PI * 2);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
    ctx.save();
    ctx.translate(-60, 0);
    drawPigNostrils(ctx);
    ctx.restore();
    ctx.save();
    ctx.translate(60, 0);
    drawPigNostrils(ctx);
    ctx.restore();
    ctx.restore();
}

function drawPigNostrils(ctx) {
    ctx.save();
    ctx.fillStyle = '#b55151';
    ctx.beginPath();
    ctx.ellipse(0, 0, 40, 60, 0, 0, Math.PI * 2);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
    ctx.restore();
}

main();

1. If you think this article is good, share and like it, so that more people can see it

2., pay attention to the official account of the kite holders, and receive learning materials (front-end “multi armed” data), regularly push you for the original in-depth text.