preface

I’ve seen a lot of Canvas tutorials, but it’s like I’ve never seen them. Here, the author introduces Canvas drawing theory and API call step by step with the geometric theory of point, line and plane (2D plane) as a foundation. After reading this article, I will no longer worry about Canvas operation.

A,

Everything you draw should start with “points,” because “points form lines, lines form surfaces,” and 2D drawings form shapes (surfaces) that are nothing more than these,

  • All shapes are combinations of lines (straight lines + arcs)
  • Shapes have three characteristics: fill, stroke, and effects
  • Everything is a plane of dense pixels

Starting with these three points, you cover most of what 2D drawing is all about.

The difference is that the geometric description of “point” is “no area.” The point’s trajectory forms a line, and in this case the line has no area. Therefore, it is important to understand that in order to present a figure visible to humans on the terminal device, it must already constitute a surface.

So when we talk about drawing a (visible) point, we’re really drawing a “solid circle,” which is essentially a face. However, this description is not conducive to the transmission or expression of information. Therefore, we need to define the concept of “point” :

  • “Point” in most cases means “solid circle.”

Having made this definition, let’s look at Canvas API from practice.

Any canvas drawing requires the following two steps:

// 1. Get the DOM element
const el = document.getElementById("canvas");
// 2. Get the drawing context
const ctx = el.getContext('2d');
Copy the code

Now that we have the drawing context, we can start to operate,

// Draw a circle with a radius of 5px at the position (top: 100, left: 100)
ctx.arc(100.100.5.0.Math.PI * 2);
// Specify the "fill" property
ctx.fillStyle = 'red';
// Perform the "Fill" operation
ctx.fill();
Copy the code

I get the following result,

Note that the canvas’s default width and height is 300 by 150px, so a red circle is drawn at (100,100).

In fact, the essence of drawing a circle on Canvas is not to draw a circle, but to draw an arc (starting from 0 and ending at 2 * PI, exactly 360°) to form a closed shape, and then fill the shape with red, which is what we called solid circle before.

The ARC API will be discussed in more detail in the “Lines” section. In short, it echoes what we said at the beginning of this article that canvas does not have points, and points are solid (filled) circles enclosed by (arc) lines.

Second, the line

Lines are divided into straight lines and arcs, and arcs can be divided into arcs and Bessel curves (curvature does not agree with arcs), which are described below.

For the record, the strict geometric definition of a line is that it has no end points and can go on indefinitely. A line is actually a “segment” (or “arc segment”), so we need to redefine the concept of a line as we explain it, just like a point.

MoveTo (x, y) is an API that moves the focus of the pen to a position that will be used as the starting point for drawing lines. This might be a little abstract, but just look at the example below.

2.1 a straight line

The API for a line is lineTo(x, y). Here is an example of a horizontal line drawn from (50, 100) to (100, 100).

  • A line of fixed width from one point on the canvas with known coordinates to another point with known coordinates.

Here’s the practice,

ctx.moveTo(50.100);
ctx.lineTo(100.100);
ctx.lineWidth = 5;
ctx.stroke()
Copy the code

The results are as follows,

The first few lines of the code are easy to understand, so let’s compare the new API to the previous one.

  • stoke(): Stroke (border)
  • fill(): fill (inside)

Since the line does not form a closed shape and we are specifying the width of the line, we can only use the “Stroke” API here.

So can we use the fill API instead, since this line looks like a rectangle with a very small width? We’ll find out in section 3 – Faces.

2.2 arc line

Now it’s time to look at the ARC API in more detail.

ctx.arc(x, y, radius, startAngle, endAngle [, counterclockwise]);
Copy the code

Let me translate that,

Arc (center x, center Y, radius, start Angle, end Angle, optional: counterclockwise or not)Copy the code

Look at an example,

ctx.arc(100.100.50.0.Math.PI);
ctx.strokeStyle="blue";
ctx.stroke()
Copy the code

The results are as follows,

Since the arc travels from 0 to Math.pi, a semicircle of 180 degrees is drawn.

See what happens when you set the Counterclockwise argument to true?

ctx.arc(100, 100, 50, 0, Math.PI, true);
Copy the code

As follows,

Now I’m going counterclockwise! (From the right, counterclockwise to the top left, then to the bottom left).

2.3 Bessel curve

The purpose of this curve is to help us draw the curve that defines the curvature. The specific operation method is a little complicated. Here, only the MDN is explained.

A Bezier curve is a mathematically described curve that is widely used in computer graphics and animation. In Vector Images, bezier curves are used to define smooth curves that can be enlarged indefinitely.

Bessel curves are described by at least two control points. In Web technology, a cubic Bezier curve is used, that is, a curve described with four control points [P0, P1, P2, P3].

ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
// The first four parameters correspond to the coordinates of the two "control points", and the last four parameters are the coordinates of the end points
Copy the code

Let’s look at an example,

// Draw a closed shape
ctx.beginPath();
ctx.moveTo(30.30);
ctx.bezierCurveTo(50.90.160, -30.200.30); / / curve
ctx.lineTo(200.100);
ctx.lineTo(30.100);
ctx.closePath();
/ / fill
ctx.fillStyle = 'lightcoral'
ctx.fill();
/ / stroke
ctx.lineWidth = 2;
ctx.strokeStyle = 'lightblue';
ctx.stroke();  
Copy the code

The results are as follows,

In this way, we can control the arc of the curve by the control points.

Three,

In Canvas, can we draw a face without drawing a border? Of course you can.

Here is also a definition of the “face”, the mathematical plane can also be extended indefinitely, here we specifically refer to the “rectangle”, namely rectangle.

Drawing a rectangle is very simple, as follows,

// Adjust the width and length of the canvas
el.height = 400;
el.width = 400; 
ctx.fillStyle = "red";
ctx.fillRect(100.100.100.200); 
Copy the code

The meanings of the four parameters are (x coordinate, y coordinate, width, height), where the coordinates specifically refer to the upper-left corner of the matrix.

The results are as follows,

This is how you draw a face directly on the canvas.

Now to answer the question posed in section 2, how do we draw a line by drawing a matrix? After all, the line here is essentially a face.

It’s really simple, just set a very small width (or height), for example, if we want to draw the exact same line in section 2, just do this,

ctx.fillStyle = "black";
ctx.fillRect(50.100.50.5); 
Copy the code

Draw a line of length 50 and width 5 from position (50,100) and look at the result,

Is it exactly the same

Four, eggs

Canvas’s basic API allows you to add points, lines, and surfaces to the canvas, as well as images and text directly. The following is an example of adding text.

ctx.fillStyle = "black";
ctx.font = "italic 14pt Arial";
ctx.fillText("hello canvas".20.20);
Copy the code

The effect is as follows,

To set a linear gradient in the Canvas, use the createLinearGradient and addColorStop apis

ctx.createLinearGradient(x0, y0, x1, y1);
gradient.addColorStop(offset, color);
Copy the code

Here’s an example.

// Set the color
const grad = ctx.createLinearGradient(0.0.200.0);
grad.addColorStop(0."lightgray");
grad.addColorStop(0.2."lightblue");
grad.addColorStop(0.6."blue");
grad.addColorStop(1."black");
// Add color
ctx.fillStyle = grad;
ctx.fillRect(0.0.200.200);
Copy the code

The effect is as follows,

Using the above two examples, we can draw gradient text by changing the fillStyle of the text to grad

The over!

Afterword.

After reading this article, do you feel that you have a deeper understanding of Canvas? If you think it is useful, please help to click 👍 ~

In the future, more in-depth canvas API or WebGL related tutorials will be released. Click “Follow” to get the latest articles in the first time.