Five minutes to learn the basics of Canvas (II)

Please add the author's WeChat official account. If there are new articles in the future, they will be pushed to you directly on the WeChat official account. Thank you very much.


0. Preface

I believe that after reading the previous article, you have some knowledge and understanding of the basis of Canvas, but you must remember that I left a small hole in the previous article.

The reason why I didn't tell you how to draw a circle is that the CanvasRenderingContext2D object only provides two methods to draw a rectangle, and doesn't directly provide methods to draw circles, ellipses and other geometric figures. In order to draw more complex methods on Canvas, you must enable paths on Canvas and borrow paths to draw graphs.

Now let's take a look at how to use paths to draw circles and other figures.

------------------I am the gorgeous dividing line----------------------

The next article previews various image effects of canvas.

In addition, in the next period of time, the editor will enjoy the holiday, and will not update readers for the time being. I hope you will wait patiently.

1. Use path

To use the path on Canvas, follow the steps below.

  1. Call the beginPath() method of the CanvasRenderingContext2D object to start defining the path.
  2. Call various methods of CanvasRenderingContext2D to add sub paths.
  3. Call the closePath method of CanvasRenderingContext2D to close the path.
  4. Call the fill () or stroke () method of CanvasRenderingContext2D to fill the path or draw the path border.

Then we have made it clear how to use the path. Next, we will introduce the method of adding sub paths in canvas.

- -
arc(float x,float y,float radius,float startAngle,float endAngle,boolean counterclockwise) Adds an arc to the current path of canvas. Draw an arc starting from the startAngle angle and ending at the endAngle angle with x, y as the center and radius as the radius. StartAngle and endAngle are in angles.
arcTo(float x1,float x2,float y1,float y2,float radius) Adds an arc to the current path of canvas. The only difference from the previous method is that the arc is defined in a different way.
bezierCurveTo(float cpX1, float cpY1, float cpX2, float cpY2, float x, float y) Add a Bezier curve to the current path
quadraticCurveTo(float cpX, float cpY,float x,float y) Add a quadratic Bezier curve to the current path of canvas
rect(float x, float y,float width, float height) Add a rectangle to the current path of canvas

These are the methods, but there are many parameters. Let's take a look at the specific use of these methods one by one.

1.1 Draw circle

First, let's learn how to draw a circle. First, let's make it clear that we should use the arc () method, then how should we use this method?

Let's put "yards" here.

 <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div> <h2>Draw Circle</h2> <canvas id="canvas_1" width="1000" height="500" style="box-shadow: 0px 0px 20px black;"> The current browser does not support canvas </canvas> </div> </body> <script type="text/javascript"> //Get the DOM object corresponding to the canvas element var canvas_1 = document.getElementById("canvas_1"); //Get the canvas RenderingContent2D object drawn on canvas var ctx = canvas_1.getContext("2d"); //Let's draw more circles and use the for loop for(var i = 0; i < 10 ; i++){ //Start defining path ctx.beginPath(); //Add an arc ctx.arc(i * 25,i * 25,(i + 1) * 8, 0, Math. PI * 2, true); //Close Path ctx.closePath(); //Set Fill Color ctx.fillStyle = 'rgba(255,0,255,'+ (10 - i) * 0.1 + ')'; //Fill current path ctx.fill(); } </script> </html>

The final results are as follows:

Paste_Image.png

I wonder if the kids understand the above procedure?

It doesn't matter if you don't understand it. Let's talk about the difficulties in the above content.

First of all, Math PI actually refers to π, in other words, 180 °, so the angle we used above is Math PI * 2, that is, a circle is drawn.

Later arc(float x,float y,float radius,float startAngle,float endAngle,boolean counterclockwise) This method.

There are 6 parameters in total. These six parameters actually correspond to:

- -
float x Specifies the X coordinate of the center of the arc
float y Specifies the Y coordinate of the center of the arc
float radius Specify radius of arc
float startAngle Set the start angle of the arc
float endAngle Set the ending angle of the arc
boolean counterclockwise Set whether to rotate clockwise

In this way, I wonder if you are clear about our circle drawing?

If you have any questions, please leave a message and reply immediately.

1.2 Draw rounded rectangle

We have learned to draw circles and rectangles before, and even we can modify the rounded corners of our elements through lineJoin.

However, we don't need fixed things. What we really need is content that can be customized according to the effect we want.

To do this, we can also use arcTo to draw an arc.

 <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div> <h2>Draw Circle</h2> <canvas id="canvas_1" width="1000" height="500" style="box-shadow: 0px 0px 20px black;"> The current browser does not support canvas </canvas> </div> </body> <script type="text/javascript"> /* This method is responsible for drawing a rounded rectangle X1, y2: coordinates of the upper left corner of the rounded rectangle Width, height: control the width and height of the rounded rectangle Radius: control the radius of the four fillets of the rounded rectangle */ function creatRoundRect(ctx, x1, y1, width, height, radius){ //Move to the start point in the upper left corner ctx.moveTo(x1 + radius, y1); //Add a line segment connecting the start point to the upper right corner ctx.lineTo(x1 + width - radius, y1); //Add an arc in the upper right corner ctx.arcTo(x1 + width, y1, x1 + width, y1 + radius, radius); //Add a line segment connected to the lower right corner ctx.lineTo(x1 + width, y1 + height - radius); //Add an arc in the lower right corner ctx.arcTo(x1 + width, y1 + height, x1 + width - radius, y1 + height, radius); //Add a line segment from the lower right corner to the lower left corner ctx.lineTo(x1 + radius, y1 + height); //Add lower left arc ctx.arcTo(x1, y1 + height, x1, y1 + height - radius,radius); //Add a line segment from the lower left corner to the upper left corner ctx.lineTo(x1, y1 + radius); //Add an arc ctx.arcTo(x1, y1, x1 + radius, y1, radius); ctx.closePath(); } //Get the DOM object corresponding to the canvas element var canvas_1 = document.getElementById("canvas_1"); //Get the canvas RenderingContent2D object drawn on canvas var ctx = canvas_1.getContext("2d"); ctx.lineWidth = 3; creatRoundRect(ctx, 30, 30, 200, 100, 20); ctx.stroke(); </script> </html>

Note that I have drawn four lines and four arc angles here, and connected them end to end to achieve the function of drawing a rectangular box.

Secondly, a function is specially encapsulated to draw a rounded rectangle. If you need it, you can paste it directly.

Paste_Image.png

1.3 Drawing a polygon

Do you remember drawing triangles before?

When we draw triangles, we mainly use the lineTo and moveTo methods, but there are far more than these kinds of figures we encounter in life.

So today we will learn how to draw a polygon.

 <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div> <h2>Draw a polygon</h2> <canvas id="canvas_1" width="1000" height="500" style="box-shadow: 0px 0px 20px black;"> The current browser does not support canvas </canvas> </div> </body> <script type="text/javascript"> /* This method is used to draw a polygon n: This parameter is usually set to an odd number to control the drawing of N-point stars Dx, dy: control the position of star N Size: control the size of the star with N angles */ function creatStar(context, n, dx, dy, size){ //Start creating path context.beginPath(); var dig = Math. PI / n * 4; context.moveTo(dx, y + dy); for(var i = 0; i <= n; i++){ var x = Math.sin(i * dig); var y = Math.cos(i * dig); //Draw a line from the current point to the specified point context.lineTo(x * size + dx, y * size + dy); } //Close Path context.closePath(); } //Get the DOM object corresponding to the canvas element var canvas_1 = document.getElementById("canvas_1"); //Get the canvas RenderingContent2D object drawn on canvas var ctx = canvas_1.getContext("2d"); //Draw Triangle Star creatStar(ctx, 3, 60, 60, 50); ctx.fillStyle = '#f00'; ctx.fill(); //Draw a five pointed star creatStar(ctx, 5, 160, 60, 50); ctx.fillStyle = '#0f0'; ctx.fill(); //Draw a seven pointed star creatStar(ctx, 7, 260, 60, 50); ctx.fillStyle = '#00f'; ctx.fill(); //Draw Nine pointed Star creatStar(ctx, 9, 360, 60, 50); ctx.fillStyle = '#f0f'; ctx.fill(); </script> </html>

It can be seen that we have encapsulated a method specially used to draw stars with multiple angles. Of course, we can also continue to expand on this basis, which depends on the play of our partners.

Paste_Image.png

1.4 Drawing curves

Remember that we learned five methods at the beginning. In addition to the drawing of circles and rounded rectangles that we have learned now, are there any strange methods?

So let's start learning these methods now.

First, let's learn how to add Bezier curves.

- -
bezierCurveTo(float cpX1, float cpY1, float cpX2, float cpY2, float x, float y) Add a Bezier curve to the current path
quadraticCurveTo(float cpX, float cpY,float x,float y) Add a quadratic Bezier curve to the current path of canvas

First, let's take a look at the first method. There are actually four points in the first method that need attention.

Paste_Image.png

They are respectively

  • Bottom left Start point
  • pinkish First control point (anchor)
  • Navy Second control point (anchor)
  • Upper right End point

In the method, cpX1 and cpY1 are the coordinates of the first control point,

The following cpX2 and cpY2 are the coordinates of the second control point.

And what about quadratic Bessel curve?

Paste_Image.png

Unlike normal Bezier, a conic only needs three points:

  • Bottom left Start point
  • Navy control point
  • Upper right End point

The cpX and cpY in the method are used to set the coordinates of control points.

Then let's try to draw flowers together.

 <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div> <h2>Draw flowers</h2> <canvas id="canvas_1" width="1000" height="500" style="box-shadow: 0px 0px 20px black;"> The current browser does not support canvas </canvas> </div> </body> <script type="text/javascript"> /* This method is responsible for drawing flowers n: This parameter controls the number of petals of the flower Dx, dy: control the position of flowers Size: control the size of flowers Length: control the length of petals */ function creatFlower(context, n, dx, dy, size, length){ //Start creating path context.beginPath(); context.moveTo(dx, dy + size); var dig = 2 * Math. PI / n; for(var i = 1; i < n + 1; i++){ //Calculate the coordinates of control points var ctrlX = Math.sin((i - 0.5) * dig) * length + dx; var ctrlY = Math.cos((i - 0.5) * dig) * length + dy; //Calculate the coordinates of the end point var x = Math.sin(i * dig) * size + dx; var y = Math.cos(i * dig) * size + dy; //Draw conic context.quadraticCurveTo(ctrlX, ctrlY, x, y); } context.closePath(); } //Get the DOM object corresponding to the canvas element var canvas_1 = document.getElementById("canvas_1"); //Get the canvas RenderingContent2D object drawn on canvas var ctx = canvas_1.getContext("2d"); //Draw a five petal flower creatFlower(ctx, 5, 70, 100, 30, 80); ctx.fillStyle = "#f00"; ctx.fill(); //Draw a six petaled flower creatFlower(ctx, 6, 220, 100, 30, 80); ctx.fillStyle = "#ff0"; ctx.fill(); //Draw a seven petal flower creatFlower(ctx, 7, 370, 100, 30, 80); ctx.fillStyle = "#f0f"; ctx.fill(); </script> </html>
Paste_Image.png

1.5 Drawing Bitmaps

Up to now, we have talked about how to draw lines, triangles, polygonal stars, rectangles, circles, flowers, rounded rectangles and other shapes.

But in addition to these basic graphics, we can also draw a "bitmap", so that a picture can be drawn on our canvas.

How can we do that?

Since we want to load our pictures into our canvas, what should we do? Let's first construct an Image object.

 var image = new Image(); image.src = "lipeng.png";

Two points should be noted,

  • Our program only creates and loads images, so we don't need to pass in the width and height when calling image, so the created image will maintain the same width and height as the image specified by the src attribute.
  • Src loads images asynchronously. If the image data is too large or comes directly from the network, when our network speed is slow, we will find that our image drawing will be very slow, which will affect users' use. We can use onload to ensure that we can draw after the image is loaded.
 var image = new Image(); image.src = "lipeng.png"; image.onload =  function(){ //Draw Picture }

After learning how to load pictures, can we add pictures to our canvas?

There is no way to add pictures.

We also need to learn how to add pictures. Here are three methods.

- -
drawImage(Image image, float x, float y) Draw the image at x and y. This method does not do any scaling on the picture, and the picture drawn remains the original size
drawImage(Image image, float x, float y, float width, float height) Draw the image at x and y. This method will scale the picture, and the drawn width is width and height is height.
drawImage(Image image, integer sx, integer sy, integer sw, integer sh, float dx, float dy,float dw, float dh) This method will "dig" a piece from the image and paint it on the canvas. The sx and sy parameters control where to start digging from the original image, and the sw and sh parameters control the width and height of the digging ball from the original image; The two parameters, dx and dy, control where the extracted picture is drawn on the canvas, while dw and dh control the scaling of the drawn picture. The drawn width is dw and the height is dh

Now that we know the method, let's learn how to implement it in code.

 <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div> <h2>Draw Bitmap</h2> <canvas id="canvas_1" width="1000" height="500" style="box-shadow: 0px 0px 20px black;"> The current browser does not support canvas </canvas> </div> </body> <script type="text/javascript"> //Get the DOM object corresponding to the canvas element var canvas_1 = document.getElementById("canvas_1"); //Get the canvas RenderingContent2D object drawn on canvas var ctx = canvas_1.getContext("2d"); //Create an image object var image = new Image(); //Create an image object to load pictures image.src = "lipeng.png"; //This function is triggered when the picture is loaded image.onload = function(){ //Draw the picture at its original size ctx.drawImage(image, 20, 10); //Zoom when drawing pictures ctx.drawImage(image, 600, 10, 76, 110); //Dig out a piece from the original picture, enlarge it three times and draw it on canvas var sd = 50; var sh = 50; /* Parameter Description Image image, integer sx, integer sy, integer sw, integer sh, float dx, float dy,float dw, float dh The two parameters, sx and sy, control where to start digging from the original image, Two parameters, sw and sh, control the width and height of the digging ball from the original image; Two parameters, dx and dy, control where the excavated image is drawn on the canvas Dw and dh control the scaling of the drawn picture. The drawn width is dw and the height is dh */ ctx.drawImage(image, 230, 220,sd, sh, 765, 10, sd * 3, sh * 3); } </script> </html>

The results are as follows:

Paste_Image.png

How about that? Do you feel that you have grown up in an instant? Hurry up and learn.

Last edited on
© The copyright belongs to the author. Please contact the author for reprinting or content cooperation
  • Preface: In the late 1970s, a skinning case shocked the whole city of Binhe, and several subsequent cases caused great panic in Binhe. Liu Yan, an old criminal policeman, will take you to solve it
    Shen Nian sama read 158,736 comment four fabulous three hundred and sixty-two
  • Preface: There were three consecutive deaths in Binhe. The death scene was strange and strange, and all of them were accidental deaths. The police found that the dead were all
    Shen Nian sama read 67,167 comment one fabulous two hundred and ninety-one
  • Wen/Pan Xiaolu As soon as I entered the store, Wang Yugui, the shopkeeper of Xixi Building, came up to me with a worried face
    Kaifeng First Lecturer read 108,442 comment zero fabulous two hundred and forty-three
  • Wen/Not bad Uncle Tu, my name is Zhang Ling, and I am the Taoist Priest of Tianyi Taoist Temple. A pilgrim often asks me, Taoist Priest, what is the most difficult demon in the world? I laugh instead of
    Kaifeng First Lecturer read 43,902 comment zero fabulous two hundred and four
  • In order to forget my predecessor, I held the wedding at once. As a result, my husband's sister dressed more like a bride than I did. I have always comforted myself that they just have a good relationship, but when I
    Tea Story read 52,302 comment three fabulous two hundred and eighty-seven
  • I will uncover the white cloth. She just lay there quietly, as if asleep. The red wedding dress sets off the skin like snow. The combed lines on the untidy hair, one
    Kaifeng First Lecturer read 40,573 comment one fabulous two hundred and sixteen
  • That day, I went to the river to look for ghosts with my camera and recording. Smile to death, a fat man bragged in front of me, but I did all the bragging. I am a ghost spotting anchor, and I will
    Shen Nian sama read 31,847 comment two fabulous three hundred and twelve
  • Wen/Canglan Xiangmo suddenly opened my eyes and sighed: "It was a nightmare..."
    Kaifeng First Lecturer read 30,562 comment zero fabulous one hundred and ninety-seven
  • Preface: A couple in Vang Vieng, Laos disappeared. The missing person was Zhang Zhixin (not his real name) and his girlfriend Liu Ying. Unexpectedly, half a month later, a local people found a corpse in the forest
    Shen Nian sama read 34,260 comment one fabulous two hundred and forty-one
  • Text Living Alone in the Wilderness Mountains, the forest keeper died strangely, and there were 42 bloody pustules on the body... Initial Seal · Zhang Xun The following content is from the perspective of Zhang Xun on September 15
    Tea Story read 30,531 comment two fabulous two hundred and forty-five
  • Song Qinglang and I have been in love for three years. When we tried our wedding dress, we found that we were green. My college friend sent me a photo of my fiance having dinner with Bai Yueguang
    Tea Story read 32,021 comment one fabulous two hundred and fifty-eight
  • Preface: A man who was originally alive and kicking died in a strange and horrible way. The body in the mourning hall suddenly broke out of the coffin. Whether it was a fake body or something else, I am Ning Ze, a criminal policeman, with
    Shen Nian sama read 28,367 comment two fabulous two hundred and fifty-three
  • In the text year, the government announced that the nuclear power plant located on F Island was affected by a magnitude 9 earthquake and radioactive substances leaked. R himself ate the bad consequences, but gave the world environment
    Tea Story read 33,016 comment three fabulous two hundred and thirty-five
  • Text/On the first and ninth days of Mengmeng, I lay on a hidden roof in the doghouse and looked around. The courtyard is really bustling, with spring flowers like brocade and voices like boiling. The master of the Chuang Tzu today did "Spring Day..."
    Kaifeng First Lecturer read 26,068 comment zero fabulous eight
  • Wen/Canglan Fragrant Ink I looked up at the sun in the sky. At the end of March, it was as warm as spring. The moment I stepped out of the prison with a layer of jacketed jacket, I was already sweating. A sound of footsteps
    Kaifeng First Lecturer read 26,827 comment zero fabulous one hundred and ninety-four
  • I was cheated by a black hearted intermediary to work in Thailand, but I was almost squeezed dry by the siren princess just after getting off the plane... 1 My name is Wang Buliu, a native of Northeast China. A month ago, I also
    Shen Nian sama read 35,610 comment two fabulous two hundred and seventy-four
  • I was born in a brothel, but I just looked like the princess, so I was forced to go to the enemy country and make friends instead of her. It is said that my marriage partner is a disabled prince, but the wedding night
    Tea Story read 35,514 comment two fabulous two hundred and sixty-nine

Recommended reading More highlights

  • 1: Introduction to canvas 1.1 What is canvas? ①: Canvas is a new tag provided by HTML5 ②: HTML5
    GreenHand1 read 4,606 comment two fabulous thirty-two
  • Various postures of Android customized view 1 Display of activity ViewRootImpl Details Activity
    passiontim read 170,567 comment twenty-five fabulous seven hundred and seven
  • Preface Customized View is the foundation that Android developers must understand; The use of Canvas class plays a very important role in custom View drawing
    Carson takes you to learn Android read 27,125 comment seven fabulous two hundred and eighteen
  • (Simple Book - Reward) Beautiful articles are rewarded into the bag. I didn't sleep last night to read simple books. Look around and give a reward of two hundred and six. Silent hard work is not good, and little work is good. life...
    Gan Chaowu read four hundred and forty-eight comment zero fabulous zero
  • Open a "fruit book": have healthy fruit and vegetable juice; Nutrition paperback book; A mailbox can collect your troubles, and they will also get careful feedback; The male shopkeeper loves music
    Little little little monkey read one hundred and eight comment zero fabulous zero