2.2.4 HTML5 Canvas drawing basics

2.2.4 HTML5 Canvas drawing basics

Canvas is a new feature added when the HTML standard is developed to HTML5 in recent years, and is used for efficient drawing on web pages. H5 canvas drawing is similar to drawing steps such as MFC (Microsoft Foundation Classes) or Visual Basic. The following example gives an example of drawing a straight path, filling and outputting text on a canvas. The HTML text includes a canvas for drawing:

1. <html lang="en">

2. <head>

3. <meta charset="UTF-8">

4. <title>CH2: Canvas Demo </title>

5. <script type="text/javascript"src="CH2CanvasBasic.js"></script>

6. </head>

7. <body>

8. <div style="position:absolute; top: 50px; left: 50px;">

9. <canvas id="canvasOne"width="600"height="400">

10. Yourbrowser does not support HTML 5 Canvas.

11. </canvas>

12. </div>

13. </body>

14. </html>

The corresponding js script file CH2CanvasBasic.js is as follows:

1. window.addEventListener("load", main, false);//Execute the main function after the window is loaded

2.//Graphic drawing is similar to the drawing interface in Microsoft MFC library

3. function main () {//Main program entry

4. var theCanvas = document.getElementById("canvasOne");//Get canvas instance

5. var context = theCanvas.getContext("2d");//Get 2D drawing environment operation interface

6. context.stokeStyle = "red";//The line color is set to red red

7.

8. context.beginPath();//Start drawing path

9. context.moveTo(20, 10);//move to

10. context.lineTo(40,200);//line to

11. context.lineTo(140,180);//line to

12. context.stroke();//Display path

13.

14. context.fillStyle ='green';//Set the fill color to green

15. context.fillRect(90,40, 180, 90);//Draw a rectangle and set its upper left corner coordinates and length and width

16.

17. context.font = '28px microsoft yahei';//Set font and size

18. context.fillText('This is the sample text drawn by Canvas', 100, 30);//Draw the customized text

19.}

Save these two texts on the hard disk, open them with EDGE, and get the following results:

We have less content here, if you are interested, you can refer to the tutorials on the Internet.

Reference: https://cloud.tencent.com/developer/article/1177734 2.2.4 HTML5 Canvas Drawing Basics-Cloud + Community-Tencent Cloud