When we learn a new thing, we often only touch the most basic things, most of the entry is really just the entry, it is difficult to associate with the realization of some practical application cases under the premise of no practical application experience, feeling learned or not learned almost. That this paper will not only give you some Canvas API, as well as some basic graphics rendering, also to show you some Canvas practical application case, introduces the general idea of implementing and lead you to understand the Canvas at the same time, the application of it to realization have some idea, when you have the insight, state be far behind?

1. What is Canvas

MDN: Is a new element in HTML5 that can be used to draw graphics using scripts in JavaScript. For example, it can be used to draw graphics, make photos, create animations, and even do real-time video processing or rendering.

2. Canva application scenarios

  1. Visual diagrams. For example: Echarts
  2. All kinds of awesome and fucked-out scene animations.
  3. Scene activity page (Scratch-off, rotary draw, red envelope rain)
  4. H5 mini-game (Backgammon, Tetris)
  5. Graphic Editor (Web version online Ps)

Introduction to three,

(1) Set the canvas

// html
<canvas id="canvas"></canvas>
Copy the code

The initialized canvas has a default size of 300×150. We can also set the size of the canvas manually. There are three ways to set the canvas:

  • HTML set width, height;
  • CSS set width and height;
  • JS dynamically set width, height.

Let’s look at it in a couple of ways:

/ / HTML
<canvas width="400" height="200"></canvas>

/ / CSS style
#canvas{
    width:400px;
    height:200px
}

/ / js
var canvas = document.getElementById("canvas");
canvas.width = 400;
canvas.height = 200;
Copy the code

Doesn’t it look easy? That’s right. How else did you get there?

Note: among the three methods, HTML and JS actually change the size of the canvas, while CSS only changes the size of the canvas element. In fact, the canvas is still 300×150, which can be understood as displaying 300×150 content in a 400×200 container, which will lead to deformation of the graph.

????? Don’t understand?

Mona Lisa’s smile is getting serious!

(2) Point, line and plane

This completes the most basic premise of Canvas manipulation – setting up the Canvas. Next, I will introduce some basic knowledge about graphics – point, line and plane and how to draw point, line and plane using Canvas.

  • Point: In geometry, point only has position, but in morphology, point also has size, shape, color, texture and other modeling elements.

  • Line: Line is the track of point movement and the starting point of surface movement

  • Surface: An enlarged point forms a surface, and a closed line makes a surface

Basic concept introduction, good (zou) good (zou) palm (xing) grip (shi) oh ~

Let’s get down to business…

Draw – point

For the sake of learning, we will treat the point as a circle.

Want to plot on canvas, first of all, we need through the HTMLCanvasElement. GetContext () first to get the canvas element context, through the context to drawing canvas, canvas as the canvas, you can understand the context as the brush 🖌 ️.

 var canvas = document.getElementById("canvas"); // Get the element reference
 var context = canvas.getContext("2d"); // Get the canvas context
Copy the code

This mind fuck ~

<script>
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    var cx = canvas.width = 400;
    var cy = canvas.height = 200;
    
    context.beginPath(); // Start a path or reset the current path
    context.arc(100.100.20.0.Math.PI * 2.true); / / draw circles
    context.closePath(); // Create a path from the current point back to the starting point (close path)
    context.fillStyle = 'RGB (255255255).; // Fill the style
    context.fill(); // Start drawing or filling
</script>
Copy the code

Take a look at the results:

That’s a bit big! , worried that you see grandpa too much effort to find a point, I deliberately painted it a little bigger.

Here we mainly use the Arc () method, which is used to create arcs/curves (create circles or partial circles).

context.arc(x,y,r,sAngle,eAngle,counterclockwise);

  • X: The x-coordinate of the center of a circle
  • Y: The y coordinate of the center of a circle
  • R: radius of the circle.
  • SAngle: The starting Angle, measured in radians. The three o ‘clock position of the circle of the arc is 0 degrees.
  • EAngle: End Angle, measured in radians.
  • Counterclockwise: optional. Specifies whether to draw counterclockwise or clockwise. False = clockwise, true = counterclockwise.

So if we were to draw a semicircle we could do this

context.arc(100.100.20.0.Math.PI * 1.0.false); // so easy~ 
Copy the code

The effect is shown in figure

We mentioned that arc() can also be used to draw arcs, so how do you do that? Please look at the code

context.beginPath(); Context. The arc (100,75,50,0,1.5 * math.h PI); Context.strokestyle ="red" // Set the stroke color to red context.stroke(); // Take the routeCopy the code

The effect is shown in figure

Careful small partners to here may have found some clues ~

In addition to changing the Angle, we mainly replace fillStyle and fill() with strokeStyle and stroke().

A fill is a fill and a stroke is a stroke.

If this feels like “oh ~”, look back and see if we’re missing a line of code

context.closePath()

So let’s add it to see what happens:

context.beginPath();
context.arc(100.75.50.0.1.5*Math.PI); 
context.closePath(); // Close the path
context.strokeStyle="red" // Set the stroke color to red
context.stroke(); // Take the route
Copy the code

ClosePath () makes the difference between adding closePath() to a graph that is not filled. ClosePath () does not matter if the image is filled with a closePath(). It fills a closed area, just like the color in Photoshop. If you do not add closePath(), it will be closed by default.

context.beginPath();
context.arc(100.75.50.0.1.5*Math.PI); 
context.fillStyle="red" // Set the stroke color to red
context.fill(); // Take the route
Copy the code

Drink a glass of water and let’s see draw a straight line!

Draw – Line

We just introduced that a line is the trajectory of a point. How many points do we have to draw on this line? Don’t be so deng!

Two points and one line. If we want to draw a line, we first have to identify two points, and before we draw it, we’ll introduce two methods

context.moveTo(x,y); // Set the starting point

context.lineTo(x,y); // Set the first point

  • X: indicates the x coordinate of the destination position of a path
  • Y: indicates the y coordinate of the destination position of a path

Without further ado, get straight to the code:

context.beginPath(); // Start a path
context.moveTo(50.50); // Draw the starting position of the line
context.lineTo(100.100); // Add a new point, then create a line from the previous point to that point on the canvas
context.stroke();
Copy the code

The effect is shown in figure

Note: If moveTo() is not set, the first lineTo() will act as moveTo. Such as:

context.beginPath();
context.lineTo(20.20);
context.lineTo(60.60);
context.lineTo(120.80);
context.lineTo(50.100);
context.stroke()
Copy the code

The effect is shown in figure

To draw a line is to connect each point in sequence,

Draw – Rectangle

context.beginPath();
context.fillStyle = '#fff'; 
context.fillRect(10.10.100.100); // Draw a solid rectangle
context.strokeStyle = '#fff'; / / line
context.strokeRect(130.10.100.100); // Draw a hollow rectangle
Copy the code

The effect is shown in figure

context.fillRect(x,y,width,height);

context.strokeRect(x,y,width,height);

  • X: the x-coordinate of the upper left corner of the rectangle
  • Y: y coordinate of the upper left corner of the rectangle
  • Width: the width of the rectangle, in pixels
  • Height: The height of the rectangle, in pixels

Another method for rectangles is to empty a given rectangle of a given pixel.

The context. ClearRect (x, y, width, height).

Let’s see it in action:

ctx.fillStyle="# 000";
ctx.fillRect(0.0.300.150); // Draw a rectangle 300 wide and 150 high
ctx.clearRect(20.20.100.50); // Clear a 100x50 area
Copy the code

The effect is shown in figure

Remember this method, this guy has great use ~!

At this point, we are done with the basics of drawing. You also have a certain understanding of canvas, do you have some ideas about drawing? Next, let’s look at some of the properties and methods that make our graphics look better. Due to space constraints, I will first list some commonly used properties and methods, and then give you a comprehensive example.

Colors, styles, and shadows

attribute describe
fillStyle Sets or returns the color, gradient, or mode used to fill the painting
strokeStyle Sets or returns the color, gradient, or mode used for the stroke
shadowColor Sets or returns the color used for the shadow
shadowBlur Sets or returns the level of blur used for shadows
shadowOffsetX Sets or returns the horizontal distance of the shadow from the shape
shadowOffsetY Sets or returns the vertical distance of the shadow from the shape


methods describe
createLinearGradient() Create a linear gradient (for canvas content)
createPattern() Repeats the specified element in the specified direction
createRadialGradient() Create a radial/circular gradient (for canvas content)
addColorStop() Specifies the color and stop position in the gradient object


Line style

methods describe
lineCap Sets or returns the end – end style of the line
lineJoin Sets or returns the type of corner created when two lines intersect
lineWidth Sets or returns the current line width
miterLimit Sets or returns the maximum miter length

The sample to the

ctx.beginPath(); // Start drawing
ctx.arc(100.100.20.0.Math.PI * 2.true); / / draw circles
var grdRound = ctx.createRadialGradient(50.80.30.0.120.120); // Create a radioactive gradient
grdRound.addColorStop(0."#CAC531"); // Add the first gradient color
grdRound.addColorStop(1."#F3F9A7"); // Add gradient second color
ctx.fillStyle = grdRound; // Set the fill style to gradient
ctx.shadowColor = "#CAC531"; // Set the shadow color
ctx.shadowBlur = 20; // Set the shadow blur
ctx.fill();  

ctx.beginPath();
ctx.lineCap = "round"; // Set the end of the line to a rounded corner
ctx.arc(100.100.50.Math.PI * 0.1.Math.PI * 0.6); / / draw circles
ctx.lineWidth = 10; // Set the line width
ctx.strokeStyle = "#43c6ac"; // Set the line color
ctx.stroke()

ctx.beginPath();
ctx.moveTo(130.160); / / draw circles
ctx.lineTo(210.320);
ctx.lineWidth = 10;
var grdLine = ctx.createLinearGradient(130.160.210.320); // Create a linear gradient
grdLine.addColorStop(0."#43c6ac");
grdLine.addColorStop(1."#CAC531");
ctx.strokeStyle = grdLine; // Set gradient
ctx.stroke()
Copy the code

The effect is shown in figure

Er…

More than I thought it would be

What I want to draw is actually the ️ scepter in Loki’s hand, which as you can see is very close.

I shouted: “Canvas, cow *”.

Anyway, apart from seeing some common attributes and methods used, is there any other inspiration? Drawing on canvas is the same as drawing on white paper. For example, if I want to draw a red sun, I must use a red crayon to draw the sun. After drawing the sun, I want to draw a grass.


This is the basis of the introduction of ~

Now think about what I said at the beginning of this article. After getting the basics right, do you have any ideas about how to implement canvas applications or effects? Huh? One second, feel oneself learned again, calm down to think, after a second have feeling what also can’t think. It’s a terrible feeling.

Don’t worry, let’s take a look at some practical applications to give you some ideas.

Iv. Canvas application case

Scratch music

Let’s take a look at the effect

Before analyzing the implementation idea, I will introduce a canvas method drawImage(), which has three uses

1. Position the image on the canvas:

context.drawImage(img,x,y,width,height);

2. Position the image on the canvas and specify the width and height of the image:

context.drawImage(img,x,y,width,height);

3. Cut the image and position the clipped part on the canvas:

context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);

Method draws an image, canvas, or video on a canvas. Can also draw parts of an image and/or increase or decrease the size of the image.

  • Img: Specifies the image, canvas, or video to use.
  • Sx: optional. The x position at which the shear began.
  • Sy: optional. The y position where the shear started.
  • Swidth: optional. The width of the clipped image.
  • Sheight: optional. The height of the clipped image.
  • X: The x coordinate position of the image on the canvas.
  • Y: The y coordinate position of the image on the canvas.
  • Width: optional. The width of the image to use. (Stretch or zoom out image)
  • Height: optional. The height of the image to use. (Stretch or zoom out image)

We mainly use the second method, drawing the picture to the canvas according to the width and height of the canvas, and then absolutely positioning the canvas element on our content element.

How to shave it? Remember the clearRect() method, which is used to clean the drawing, combined with the js onMouseDown and onMousemove events to achieve the scraping effect.

😊 ~ ~ the corners of the mouth began to rise slightly ~

After drinking this bowl of porridge, I still have my stomach and eat a steamed bread.

Hack Code Rain

Same old rule. Renderings first

For recording reasons, the effect will look stuck.

But before I get to the implementation, I’ll introduce you to the fillText() method, which is used to draw colored text on a canvas. The default color of text is black.

context.fillText(text,x,y,maxWidth);

  • Text: Specifies the text to be output on the canvas.
  • X: The x-coordinate position (relative to the canvas) in which to start drawing the text.
  • Y: Start drawing the y-coordinate position of the text (relative to the canvas).
  • MaxWidth: optional. The maximum allowed text width, in pixels.
context.fillText('look at'.5.20);
Copy the code

The effect is shown in figure

We can also use the font property to set the input text as well as output text on the canvas, for example

context.font="20px Georgia"; // Set the font size to 20px, Georgia font

Now let’s analyze the effect:

Anyway, let’s put the black background on first.

Forget about the animation, let’s draw a line, how do we draw it? Once we set the font size, we can calculate how many columns we need to draw based on the container’s width. That is, we can calculate the passable parameter of x we need in fillText(). So by going through the following numbers, we can draw a line, right?

So we’re going through SettingsfillText()In the y parameter can achieve high and low scattered text effect? Fade out we draw a container size with each time we draw0.05A rectangle with a background of transparency, so that each drawing will cover up the previous drawing, and the last drawing will be a bit dim due to the effect of transparency. The last step is to get it moving. We can go throughsetInterval()Method constantly triggers the drawing, and when the drawing frequency is fast, it becomes an animation.

This case is best to write a more convenient to understand.

A rush of energy! There is one last case

gobang

Effect:

There are two main difficulties with implementation.

1) How to draw chess pieces on grid points

2) How to judge the winner

How to draw a chessboard I won’t say more, or let our brain move a little ~

First we need to set the checkerboard spacing constant: DISTANCE. So let’s draw the chessboard with this spacing.

Draw chess positions

By setting the click event to draw circles of the canvas element, painting pieces is round, has said the above, the location of the painting is the key, we can get to trigger the click event for the coordinates (event. OffsetX, event. OffsetY), that how to drawn according to the click event for the coordinates of the point?

We can at least obtain the left x-coordinate nearest to the current trigger point. Is it as follows:

Const left_x = math.floor (event.offsetx/DISTANCE) * DISTANCE // rounded down

So the extra distance is

const d = event.offsetX - Math.floor( event.offsetX / DISTANCE ) * DISTANCE ;

This distance must be less than the length of a grid, so we can determine the piece x by rounding off the offset

const x = Math.round( d / DISTANCE ) * DISTANCE + left_x;

And the same way we can figure out the y coordinates, we can draw the chess pieces.

We draw a chess piece and save the coordinate points into the corresponding array white_list and black_list.

Judge the winning or losing

There are three main cases

  • The horizontal direction
  • The vertical direction
  • Slash direction

It’s basically four linear functions

This should be your best linear function ~ ~!!

Every time when the pieces of the coordinates were taken into the calculation, from the preservation of the pieces in the number of pieces to find out the current linear function of the five pieces, and then to judge whether the five pieces together on the line!

What? How do you tell if five pieces are connected? Good, just open your mouth.

Small head melon seeds turn ~ ~

final


The sword is here. It’s up to you!


Finally, I send you a word:

When your sword detached, I hope the hair still bloom.



Can be finished, I hope to help you.

The author is also the first time to send an article, if the article has any mistakes or suggestions welcome everyone to correct ~

References:

w3school canvas

How to use Canvas to create cool background effects