Home  >  Article  >  Web Front-end  >  How to use HTML5 Canvas to draw lines such as straight lines or polylines_html5 tutorial skills

How to use HTML5 Canvas to draw lines such as straight lines or polylines_html5 tutorial skills

WBOY
WBOYOriginal
2016-05-16 15:51:481720browse

Explanation of the basic concepts of HTML5 Canvas
html5, this should not require any introduction, as any developer should be familiar with it. HTML5 is an "emerging" web technology standard. Currently, except for IE8 and below, almost all mainstream browsers (FireFox, Chrome, Opera, Safari, IE9) have begun to support HTML5. In addition, in the mobile browser market, many mobile browsers have also launched an arms race regarding "html5 support capabilities and performance." As a revolutionary web technology standard, html, coupled with the strong support of many browser manufacturers or organizations, it is conceivable that html5 will become the leader of web technology in the future.

html5, said to be "emerging", is actually not new at all. After all, the first official draft of html5 was announced as early as 2008. Counting from 2008, it has been quite a while now. However, so far, for most developers, it is still "big thunder but little rain" - there are many people hearing about HTML5, but very few actually use HTML5.

As we all know, many new features have been added to html5. Among the many features of html5, Canvas should be regarded as one of the most eye-catching new features. We use the Canvas object of html5 to draw graphics directly on the browser web page. This means that the browser can display graphics or animations directly on the web page without third-party plug-ins such as Flash.

Now, let’s introduce to html5 beginners how to use html5 Canvas to draw basic graphics.

First, we need to prepare the following basic html code:

XML/HTML CodeCopy content to clipboard
  1. >
  2. <html>
  3. <head>
  4. <meta charset="UTF- 8"> 
  5. <title>HTML5 Canvas Getting Started Exampletitle>
  6. head>
  7. <body>
  8. body>
  9. html>

The above code is a basic code template for an html5 page. Among them, the first line of code is a document type tag instruction, which is also the standard document type instruction for html5 pages. It is used to tell the browser "This is an html5 page. Please parse and display it according to the html5 web page standards." this page". The fourth line of code is used to tell the browser "the character encoding of this html5 page is UTF-8". This is also the standard way of writing the character encoding for html5 web pages. This is different from previous HTML character encoding instructions.

XML/HTML CodeCopy content to clipboard
  1. <meta http-equiv=" Content-Type" content="text/html;charset=UTF-8">

Now, we will explain the example of Canvas drawing graphics in the html file containing the above code. First, we add the following canvas tag to the body part of the above html code.

XML/HTML CodeCopy content to clipboard
  1. >
  2. <html>
  3. <head>
  4. <meta charset="UTF- 8"> 
  5. <title>HTML5 Canvas Getting Started Exampletitle>
  6. head>
  7. <body>
  8. <canvas id="myCanvas" width="400px" height="300px" style="border: 1px solid red;">
  9. Your browser does not support the canvas tag.
  10. canvas>
  11. body>
  12. html>

At this time, if we use a browser that supports HTML5 to open the page, we will see the following content:
2016314110155998.png (455×321)

In HTML5, the canvas tag itself does not have any behavior, it just occupies a specified size of blank space on the page. The canvas tag is equivalent to a blank canvas. We also need to use the canvas API provided by JavaScript to write the corresponding code to draw the graphics we want on this canvas.

Note: The text content in the canvas tag will be displayed in browsers that do not support HTML5. As shown in the above HTML code, if your browser does not support the canvas tag of HTML5, the text "Your browser does not support the canvas tag" will be displayed at the canvas tag.
As "painters", we first need to be familiar with the brush in our hands, which is the Canvas object in JavaScript and its related contents.

In HTML5, a canvas tag corresponds to a Canvas object. We can use regular functions such as document.getElementById() in JavaScript to obtain the object. It is worth noting that in JavaScript, we do not directly operate the Canvas object, but obtain the corresponding graphics drawing context object CanvasRenderingContext2D through the Canvas object, and then we use the many graphics drawing functions that come with the CanvasRenderingContext2D object to draw.

It’s like each canvas corresponds to a brush. If we want to draw on the canvas, we must first get the corresponding brush, and then use this brush to draw on the canvas. The CanvasRenderingContext2D object is equivalent to this brush. Now, let's try to get this brush in JavaScript.

XML/HTML CodeCopy content to clipboard
  1. >
  2. <html>
  3. <head>
  4. <meta charset="UTF- 8"> 
  5. <title>HTML5 Canvas Line Drawing Getting Started Exampletitle>
  6. head>
  7. <body>
  8. <canvas id="myCanvas" width="400px" height="300px" style="border: 1px solid red;">
  9. Your browser does not support the canvas tag.
  10. canvas>
  11. <script type="text/ javascript">
  12. //Get the Canvas object (canvas)
  13. var canvas = document.getElementById("myCanvas");
  14. //Simply detect whether the current browser supports the Canvas object to avoid prompting syntax errors in some browsers that do not support html5
  15. if(canvas.getContext){
  16. //Get the corresponding CanvasRenderingContext2D object (brush)
  17. var ctx = canvas.getContext("2d");
  18. }
  19. script>
  20. body>
  21. html>

As shown in the above code, we can use the getContext() method of the Canvas object to obtain the CanvasRenderingContext2D object. More attentive readers should have noticed: the getContext() method needs to pass in a string - 2d, and the name of the CanvasRenderingContext2D object obtained also contains 2D. This is because currently html5 only supports 2D drawing, but 3D or other forms of drawing may also be supported in future html5. At that time, we may need to use getContext("3d") to obtain the CanvasRenderingContext3D object and draw 3D graphics.

Use html5 canvas to draw lines (straight lines, polylines, etc.)
The main properties and methods of the CanvasRenderingContext2D object required to draw straight lines using html5 Canvas (those with "()" are methods) are as follows:

属性或方法 基本描述
strokeStyle 用于设置画笔绘制路径的颜色、渐变和模式。该属性的值可以是一个表示css颜色值的字符串。如果你的绘制需求比较复杂,该属性的值还可以是一个CanvasGradient对象或者CanvasPattern对象
globalAlpha 定义绘制内容的透明度,取值在0.0(完全透明)和1.0(完全不透明)之间,默认值为1.0。
lineWidth 定义绘制线条的宽度。默认值是1.0,并且这个属性必须大于0.0。较宽的线条在路径上居中,每边各有线条宽的一半。
lineCap 指定线条两端的线帽如何绘制。合法的值是 "butt"、"round"和"square"。默认值是"butt"。
beginPath() 开始一个新的绘制路径。每次绘制新的路径之前记得调用该方法。它将重置内存中现有的路径。
moveTo(int x, int y) 移动画笔到指定的坐标点(x,y),该点就是新的子路径的起始点
lineTo(int x, int y) 使用直线连接当前端点和指定的坐标点(x,y)
stroke(int x, int y) 沿着绘制路径的坐标点顺序绘制直线
closePath() 如果当前的绘制路径是打开的,则关闭掉该绘制路径。此外,调用该方法时,它会尝试用直线连接当前端点与起始端点来关闭路径,但如果图形已经关闭(比如先调用了stroke())或者只有一个点,它会什么都不做。

In the process of Canvas graphics drawing, we almost always set a few coordinate points in a certain order, which is the so-called drawing path, and then connect these coordinate points in a specified way according to our needs. This forms the shape we need. After we understand the above API of the CanvasRenderingContext2D object, drawing lines becomes very simple.

Use canvas to draw basic straight lines

Now, we use canvas to draw the most basic straight lines.

JavaScript CodeCopy content to clipboard
  1. "UTF-8">
  2. HTML5 Canvas Drawing Line Getting Started Example
  3. "myCanvas" width="400px" height="300px" style="border: 1px solid red;">
  4. Your browser does not support the canvas tag.

The display effect is as follows:
2016314110545325.png (473×319)

Use canvas to draw colored straight lines

As we all know, in the real world, brushes are also diverse and have various colors. Similarly, the Canvas brush CanvasRenderingContext2D object can also have various colors you need. In the above code example, if we do not specify a color, the Canvas brush defaults to the most common black.

Now we use the Canvas brush again to draw a blue straight line (based on the simplicity of the page, only the key JavaScript code is given below, please also refer to the complete code example above).

XML/HTML CodeCopy content to clipboard
  1. >
  2. <html>
  3. <head>
  4. <meta charset="UTF- 8"> 
  5. <title>HTML5 Canvas Line Drawing Getting Started Exampletitle>
  6. head>
  7. <body>
  8. <canvas id="myCanvas" width="400px" height="300px" style="border: 1px solid red;">
  9. Your browser does not support the canvas tag.
  10. canvas>
  11. <script type="text/ javascript">
  12. //Get the Canvas object (canvas)
  13. var canvas = document.getElementById("myCanvas");
  14. //Simply detect whether the current browser supports the Canvas object to avoid prompting syntax errors in some browsers that do not support html5
  15. if(canvas.getContext){
  16. //Get the corresponding CanvasRenderingContext2D object (brush)
  17. var ctx = canvas.getContext("2d");
  18.  
  19. //Start a new drawing path
  20. ctx.beginPath();
  21. //Define the starting point coordinates of the straight line as (10,10)
  22. ctx.moveTo(10, 10);
  23. //Define the end point coordinates of the straight line as (50,10)
  24. ctx.lineTo(50, 10);
  25. //Draw a straight line along the path of coordinate point order
  26. ctx.stroke();
  27. //Close the current drawing path
  28. ctx.closePath();
  29. //Draw a straight line with color
  30. ctx.moveTo(10, 30);
  31. ctx.lineTo(50, 30);
  32. //Support various expressions of css color values, such as: "blue", "#0000ff", "#00f", "rgb(0,0,255)", "rgba(0,0,255, 1)"
  33. // Various settings such as color must be called before the final drawing function stroke()
  34.  ctx.strokeStyle = "blue"
  35. ctx.stroke();
  36. //Close the current drawing path
  37. ctx.closePath();
  38. }
  39. script>
  40. body>
  41. html>

The corresponding display effect is as follows:
2016314110709116.png (433×316)

Use canvas to draw basic polylines

After we master drawing straight lines with Canvas, it will be much easier to draw polylines and other forms of lines. We just need to draw a few more path intermediate points and connect them in turn.

JavaScript CodeCopy content to clipboard

The corresponding display effect is as follows:
2016314110738804.png (424×315)

After mastering the above content, I believe you have some basic understanding of using Canvas to draw lines. Since the control of line width, transparency, etc. only requires setting a single attribute, please refer to the relevant API above and will not go into details here.

Strong note: When drawing a graphics path, be sure to call beginPath() first. The beginPath() method will clear the previous drawing path information in the memory. If you don't do this, it may have no effect on drawing a single shape, but when drawing multiple shapes (such as the two straight lines in the example above), it will lead to any unexpected results in operations such as path drawing or color filling.
In addition, beginners must pay a little attention to the closePath() method, especially the red text in the description of the closePath() method in the API table above. In the code example above for drawing a polyline, we first called stroke() and then called closePath(). In fact, when the stroke() method is called, the polyline has already been drawn, and the current drawing path has been closed, so when the closePath() method is called again, it will not use a straight line to connect the current endpoint and the starting endpoint ( In other words, closePath() here is optional, but in order to maintain good habits, it is still recommended to write it). If we exchange the order of calling stroke() and closePath(), the situation is completely different. Since closePath() is called first and the drawing path is not closed at this time, closePath() will connect the current endpoint and the starting endpoint with a straight line.

The sample code after exchanging the calling order of stroke() and closePath() is as follows:

After exchanging the calling order, the corresponding display effect is as follows:
2016314110800427.png (433×314)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn