Canvas draw lines (straight lines, polylines, etc.)

The main properties and methods of the object required to draw a straight line using html5 Canvas CanvasRenderingContext2D(the one with "()" is the method) are as follows:

Property or method basic description
strokeStyle Used to set the color, gradient, and mode of the brush's drawing path. The value of this property can be a string representing a css color value. If your drawing requirements are more complex, the value of this property can also be a CanvasGradient object or CanvasPattern object
globalAlpha Defines the transparency of the drawn content. The value is between 0.0 (completely transparent) and 1.0 (completely opaque). The default value is 1.0.
lineWidth Defines the width of the drawn lines. The default value is 1.0, and this property must be greater than 0.0. The wider line is centered on the path, half the width of the line on each side.
lineCap Specifies how the line caps at the ends of the line are drawn. Legal values ​​are "butt", "round", and "square". The default value is "butt". You can click here to see a specific example of lineCap to help you understand better lineCap.
beginPath() Start a new drawing path. Remember to call this method every time you draw a new path. It will reset the existing path in memory.
moveTo(int x, int y) Move the brush to the specified coordinate point (x,y), which is the starting point of the new subpath
lineTo(int x, int y) Use a straight line to connect the current endpoint and the specified coordinate point(x,y)
stroke(int x, int y) Draw a line in order along the coordinates of the drawn path
closePath() If the current drawing path is open, close the drawing path. Also, when this method is called, it will try to close the path by connecting the current and starting endpoints with a straight line, but if the shape is already closed (like stroke() was called first) or there is only one point, it will do nothing.

In the process of drawing Canvas graphics, almost always set several coordinate points in a certain order, that is, the so-called drawing path, and then connect these coordinate points in a specified way according to our needs to form The graphics we need. When we understand the CanvasRenderingContext2Dabove API of objects, then drawing lines is very simple.

Use canvas to draw basic straight lines

Now, let's use canvas to draw the most basic lines.

<!DOCTYPE html>
<html>
<head>
<metacharset="UTF-8">
<title>HTML5 Canvas line drawing example</title>
</head>
<body>
<!-- Add canvas tag with red border for easy viewing on the page-->
<canvasid="myCanvas"width="400px"height="300px"style="border:1px solid red;">
Your browser does not support the canvas tag.
</canvas>
<scripttype="text/javascript">
//Get the Canvas object (canvas)
var canvas = document.getElementById("myCanvas");
//Simply detect whether the current browser supports Canvas objects, so as to avoid syntax errors in some browsers that do not support html5
if(canvas.getContext){  
    //Get the corresponding CanvasRenderingContext2D object (brush)
    var ctx = canvas.getContext("2d");
   
    //Note that the coordinate system of the Canvas is: the upper left corner of the Canvas canvas is the origin (0,0), the right is the horizontal coordinate, and the downward is the vertical coordinate, and the unit is pixels (px).
   
    //Start a new drawing path
    ctx.beginPath();
    //Define the starting point coordinates of the line as (10,10)
    ctx.moveTo(10,10);
    //Define the coordinates of the end point of the line as (50,10)
    ctx.lineTo(50,10);
    //Draw a line along the path in the order of coordinate points
    ctx.stroke();
    //Close the current drawing path
    ctx.closePath();
}
</script>
</body>
</html>

 

The display effect is as follows

Use canvas to draw the most basic straight linesUse canvas to draw the most basic straight lines

Use canvas to draw colored lines

As we all know, in the real world, brushes are also varied and have a variety of different colors. Similarly, Canvas's brush CanvasRenderingContext2Dobjects can also have various colors you need. In the code example above, if we don't specify a color, the Canvas' brush defaults to the most common black.

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

<!DOCTYPE html>
<html>
<head>
<metacharset="UTF-8">
<title>HTML5 Canvas line drawing example</title>
</head>
<body>
<!-- Add canvas tag with red border for easy viewing on the page-->
<canvasid="myCanvas"width="400px"height="300px"style="border:1px solid red;">
您的浏览器不支持canvas标签。
</canvas>
<scripttype="text/javascript">
//获取Canvas对象(画布)
var canvas = document.getElementById("myCanvas");
//简单地检测当前浏览器是否支持Canvas对象,以免在一些不支持html5的浏览器中提示语法错误
if(canvas.getContext){  
    //获取对应的CanvasRenderingContext2D对象(画笔)
    var ctx = canvas.getContext("2d");  
   
    //开始一个新的绘制路径
    ctx.beginPath();
    //定义直线的起点坐标为(10,10)
    ctx.moveTo(10,10);
    //定义直线的终点坐标为(50,10)
    ctx.lineTo(50,10);
    //沿着坐标点顺序的路径绘制直线
    ctx.stroke();
    //关闭当前的绘制路径
    ctx.closePath();
    //绘制一条带颜色的直线
    ctx.moveTo(10,30);
    ctx.lineTo(50,30);
    //支持css颜色值的各种表现形式,例如:"blue"、"#0000ff"、"#00f"、"rgb(0,0,255)"、"rgba(0,0,255,1)"
    //颜色等各种设置,必须在最终的绘制函数stroke()之前调用
    ctx.strokeStyle ="blue";
    ctx.stroke();
    //关闭当前的绘制路径
    ctx.closePath();
}
</script>
</body>
</html>

 

对应的显示效果如下图

blue line drawn using canvas使用canvas绘制的蓝色直线

使用canvas绘制基本的折线

当我们掌握了Canvas绘制直线之后,绘制折线等其他形式的线条就简单多了。我们只需要多绘制几个路径中间点,并依次将它们连接起来即可。

<scripttype="text/javascript">
//获取Canvas对象(画布)
var canvas = document.getElementById("myCanvas");
//简单地检测当前浏览器是否支持Canvas对象,以免在一些不支持html5的浏览器中提示语法错误
if(canvas.getContext){  
    //获取对应的CanvasRenderingContext2D对象(画笔)
    var ctx = canvas.getContext("2d");  
   
    //开始一个新的绘制路径
    ctx.beginPath();
    //设置线条颜色为蓝色
    ctx.strokeStyle ="blue";
    //设置路径起点坐标
    ctx.moveTo(20,50);
    //定义中间点坐标1
    ctx.lineTo(60,50);
    //定义中间点坐标2
    ctx.lineTo(60,90);
    //定义中间点坐标3(这是最后一个中间点,也就是终点)
    ctx.lineTo(100,90);
    //按照绘制路径顺序连接各个坐标点
    ctx.stroke();
    //关闭绘制路径
    ctx.closePath();
}
</script>

 

对应的显示效果如下图

Polyline effect drawn using Canvas使用Canvas绘制的折线效果

掌握上述内容后,相信大家对使用Canvas绘制线条有一些基本的了解了吧。由于对线条的宽度、透明度等控制只是设置单个属性即可,请参考上面的相关API,这里就不再赘述了。

 

强烈注意:

①在绘制图形路径时,一定要先调用beginPath()beginPath()方法将会清空内存中之前的绘制路径信息。如果不这样做,对于绘制单个图形可能没什么影响,但是在绘制多个图形时(例如上面示例的两条直线),将会导致路径绘制或者颜色填充等操作出现任何意料之外的结果。

②对于closePath()方法,初学者一定要稍加注意,尤其是上面API表格中closePath()方法描述中的红色文字。在上面绘制折线的代码示例中,我们先调用了stroke(),再调用了closePath()。其实在调用stroke()方法时,折线就已经绘制好了,当前的绘制路径也就被关闭掉了,所以再调用closePath()方法时,它就不会使用直线连接当前端点和起始端点(也就是说,这里的closePath()是可有可无的,不过为了保持良好的习惯,还是建议写上)。

 

此外,如果我们交换一下stroke()closePath()的调用顺序,则情况完全不一样了。由于closePath()先调用,此时绘制路径并没有关闭,那么closePath()将会用直线连接当前端点和起始端点。

交换stroke()closePath()调用顺序后的示例代码如下:

<scripttype="text/javascript">
//获取Canvas对象(画布)
var canvas = document.getElementById("myCanvas");
//简单地检测当前浏览器是否支持Canvas对象,以免在一些不支持html5的浏览器中提示语法错误
if(canvas.getContext){  
    //Get the corresponding CanvasRenderingContext2D object (brush)
    var ctx = canvas.getContext("2d");  
   
    //Start a new drawing path
    ctx.beginPath();
    //set the line color to blue
    ctx.strokeStyle ="blue";
    //Set the coordinates of the starting point of the path
    ctx.moveTo(20,50);
    //Define the coordinates of the intermediate point 1
    ctx.lineTo(60,50);
    //Define the coordinates of the intermediate point 2
    ctx.lineTo(60,90);
    //Define the intermediate point coordinate 3 (this is the last intermediate point, which is the end point)
    ctx.lineTo(100,90);
    //Close the drawing path first. Note that a straight line will be used to connect the current and starting endpoints.
    ctx.closePath();
    //Finally, connect each coordinate point in the order of drawing path
    ctx.stroke();
}
</script>

 

After swapping the calling order, the corresponding display effect is as follows

Canvas drawing effect after swapping the calling orderCanvas drawing effect after swapping the calling order

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326226372&siteId=291194637