This is the ninth day of my participation in the First Challenge 2022

Hi, I’m the watermelon guy. Today, I will briefly talk about the basics of Getting started with Canvas.

Canvas is a technology that uses

as the display carrier and draws bitmaps through JavaScript scripts.

This is a series of articles:

Next: Canvas Simple introduction to small tutorial 2

The canvas element

Canvas, canvas, the name is very descriptive, is where we draw the image. The corresponding DOM element is

.

We use width and height to set the width and height of the Canvas element.

<canvas width="500" height="500"></canvas>
Copy the code

Width and height only support numbers in CSS pixel values (px). The default values are 300 and 150, respectively.

If you provide “100%”, it will convert to 100; If you provide a non-numeric value, the setting fails and you get the default value.

You can think of canvas getting width and height as similarparseIntProcessing.

In addition, if you manually change the width or height of the canvas, the canvas will be completely empty.

Note that the width and height of the canvas cannot be set using the style property. Style. width and style.height are actually scaled on the canvas with the width and height set. In a sense, you can think of the Canvas element as an IMG element.

The width and height of canvas cannot be set to infinite. Different browsers allow different maximum width and height. Once you go beyond that, you snap it to zero. Generally speaking, we do not need to set a large width and height, usually the maximum display width and height is about the same.

Render context

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
Copy the code

Before drawing the graph, we need to do some preparatory work by calling getContext with the Canvas element to get a render context.

It’s like getting a brush that can only be on a particular canvas.

Coordinate system

For a computer, the origin of the coordinate system is at the top left corner of the screen, down in the positive y direction and to the right in the positive X direction.

So this is a little bit different than what we did with the mathematical coordinate system, so be careful.

Let’s look at how to draw various shapes.

Draw a rectangle

ctx.fillStyle = '#f04'; / / red

ctx.fillRect(10 , 10.200.100); // Rectangle (fill)

ctx.strokeStyle = 'black';
ctx.lineWidth = 4;

ctx.strokeRect(10.10.200.100); // Rectangle (stroke)
Copy the code

Both methods pass in the upper-left position of the rectangle (10, 10) and the width and height (200 and 100).

FillRect is used to fill rectangular areas and strokeRect is used for stroke.

FillStyle is used to set the color of the fill, strokeStyle is used to set the color of the stroke, and lineWidth is used only for the lineWidth of the stroke.

The result of drawing is as follows:

This is analogous to setting a border and background for a Div element.

Dom vs. Canvas rendering

Compare Cavans to Div to represent a rectangle.

First, divs are declarative; they remain in the Dom tree and can be redrawn by the rendering engine at any time.

Once it is drawn on the Canvas, Canvas no longer cares whether it is a rectangle or not. Canvas just draws a series of pixels according to the command and does not maintain a tree formed by the drawn graph itself.

If you want to keep track of what graphics have been drawn, and how many layers have been formed, it’s up to the developer to maintain that.

Canvas will be more primitive than Dom automatic maintenance, where unnecessary backflow repainting caused by invisibility consumes performance, and will cede the right to decide whether to redraw or partially burst the bank to the developer, giving the developer more room for performance optimization.

But it also leaves developers with a lot of low-level groundwork to do.

Draw a circular

Canvas does not provide an API to draw a circle directly, but an API to draw an arc.

ctx.fillStyle = '#519D36'; / / green
ctx.beginPath();
ctx.arc(100.40.20.0.Math.PI * 2); // 0 is the starting point from the right,
ctx.fill();
ctx.stroke();
Copy the code

Drawing a graph usually requires composing a path through the subpaths described by various apis, followed by fill and stroke. The ARC method is one of the apis that describes subpaths.

Arc accepts the following parameters:

  • Center position(100, 40);
  • Radius (20);
  • The initial radian (0, the rightmost point of the circle)
  • Ending radian (Math.PI * 2, just one lap)
  • Whether it is a Boolean value drawn counterclockwise is optional. The default is false, clockwise.

After the arc method is executed, the Canvas remembers the path in its mind. The fill method is then called to fill the path, and the Stroke method to draw lines along the path.

BeginPath means we’re going to draw a new path later, so you don’t want to connect the stroke to the previous path. It’s like picking up the brush and getting ready to paint the next shape.

Of course, we didn’t draw any other paths before we drew the circle, so it’s ok to not do beginPath here.

The result of drawing is as follows:

Draw a triangle

Now that you know how to draw an arc, let’s see how to draw a line. Take drawing a triangle:

ctx.moveTo(20.20);
ctx.lineTo(60.20);
ctx.lineTo(40.40);
ctx.fill();
ctx.closePath();
ctx.stroke();
Copy the code

The first is moveTo to the coordinate (20, 20).

To moveTo is to hold the brush up and put it in the right position. It can do what beginPath does: get rid of the relationship with the previous path.

Then there is the lineTo from the current position along the lineTo the next point. Then we have a lineTo, where we draw the two sides of the triangle.

Now, if you fill, you can actually draw a triangle, because the fill logic will close the path with a straight line and then fill it, and the third edge will not exist.

This is not the case with stroke, which results in only two edges.

So we call the closePath method to join the current point in a straight line to the point we just started writing at (the point when we started writing at moveTo). You can replace this method with moveTo(20, 20) again. The two methods are equivalent.

The effect of drawing is:

At the end

This article introduces some basic knowledge of Canvas and demonstrates the basic operation of drawing rectangle, circle and triangle.

I’ll write another article later that covers other basic drawing operations.

This article was first published on my public account: front-end watermelon brother