How to modify the width, color and shape of lines in Canvas?

In Canvas, the default color of the line is black and the width is lpx, but we can add different styles to the line using related properties. Below we will explain in detail how to set the line style from three aspects: width, stroke color, and endpoint shape.

1. Set line width

The width of the line can be defined using the lineWidth attribute. The value of this attribute is a numerical value (without unit), measured in pixels. The sample code to set the width of the line is as follows:

context.lineNidth='10';

The above code sets the line width to 10.

2.Set the stroke color

Use the strokeStyle attribute to define the stroke color of the line. The value of this attribute is a hexadecimal color value or the English name of the color. The sample code for setting the stroke color is as follows:

context.strokeStyle='4f00';
context.strokeStyle='red';

In the above code, both methods can be used to set the stroke color of the line to red.

3. Set the endpoint shape

By default, the endpoints of the line are square. The shape of the endpoints can be changed through the lineCap property. The sample code is as follows:

context.1ineCap=, attribute value';
There are three values ​​for the lineCap attribute, as shown in the table.

The value of the lineCap attribute

1693389996478_Attribute value.png

Now that you understand the basic method of styling a line, let's show you how to style a line.

(1) Create C:icodekchapter02\demol3.html, create a canvas and set the width, color and endpoint shape for the line. The specific code is as follows:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <canvas id="cas" width="300" height="300">
     您的测览器不支持Canvas标签
  </canvas>
  <script>
   var context=document.getElementById('cas').getContext('2d');
   context.moveTo(10,10);          // 定义初始位置
   context.1ineTo(300,10);         // 定义连线端点
   context.lineWidth='10';         // 设置线的宽度
   context.strokeStyle='red';      // 设置线的颜色
   context.lineCap='round';        // 设置线的端点形状
   context.stroke();               // 定叉描边
  </script>
</body>
</html>

In the above code, the 15th line of code sets the width of the line to 10 pixels: the 16th line of code sets the line color to red; the 17th line of code sets the endpoint of the line to a circle.

(2) Save the code and test it in the browser. The page effect is as shown in the figure.

1693390529222_line width.png

Set line width, color, and endpoint shape

The page displays a red line, indicating that we have successfully set the style for the line.

Guess you like

Origin blog.csdn.net/cz_00001/article/details/132758355