To learn canvas, you must first know how to draw line segments, and then you can use many simple line segments to realize more complex graphics. For example, common charts, bar charts, line charts, etc. are all realized through line segments.
basic knowledgeThe basic knowledge of canvas is not much. I mainly know how to draw line segments, graphics, pictures, text, etc. Canvas can be drawn in the browser, or simple pictures can be drawn on the node server with the help of node-canvas. This article only records drawing in the browser. As for how to draw on the node side, you can check the relevant information yourself.
To draw in the browser, first define the canvas element in HTML. The default width and height are 300 * 150, which can be set by width
and height
. Note that the width and height of the canvas element style and the width and height of the canvas drawing canvas are not the same thing. This will be discussed later.
<canvas id=canvas> <p>The current browser does not support canvas, please upgrade your browser</p></canvas>
Before drawing, we must first obtain the 2D drawing context context of the current canvas, and subsequently draw by operating the context.
let canvas = document.querySelector('#canvas');if (!canvas) { throw new Error('can not find canvas element');}// Note 2d. The parameters must be lowercase; // By setting the parameters to webgl, you can get the 3d drawing context let ctx = canvas.getContext('2d');
Note: The above code snippet will be ignored in subsequent examples, and ctx
variable will be used directly to represent the 2D drawing context of the canvas.
Let’s take a look at the coordinate system in canvas 2D drawing. The upper left corner of the current canvas element is the coordinate origin (0,0), the horizontal direction to the right is the positive direction of the X-axis, and the vertical downward direction is the positive direction of the Y-axis, as shown below. You can operate the coordinate system through translation, rotation, and scale to achieve some animations. This part will be explained in detail in the animation knowledge section.
line segment When drawing a simple line segment, you usually set the style of the line segment first, such as color, line width, line endpoint style, etc. We set the global drawing style of ctx
by setting strokeStyle
, which can be rgba
or legal hexadecimal color. value, or gradient object, etc. The following code simply draws a red line segment with a width of 10 from (10,10) to (50,60).
ctx.strokeStyle = 'red';ctx.lineWidth = 10;ctx.moveTo(10, 10);ctx.lineTo(50, 60);ctx.stroke();
Let’s first look at the methods and properties related to drawing line segments.
Related properties:
Related methods:
Try setting different lineCap
values to draw the same line segment
ctx.lineWidth = 10;ctx.textAlign = 'center';let colors = ['red', 'green', 'blue'];let lineCaps = ['butt', 'round', 'square'];for ( let [index, lc] of lineCaps.entries()) { ctx.strokeStyle = colors[index]; //Set the color of the line segment ctx.lineCap = lc; //Set lineCap ctx.beginPath(); // Clear the current path ctx.moveTo(10, 20 + 20 * index); ctx.lineTo(50, 20 + 20 * index); ctx.stroke(); ctx.fillText(lc, 80 , 25 + 20 * index);}
As can be seen from the results in the above figure, when lineCap
is set to round and square, endpoints of a certain length will be added to both ends of the original line segment, except that round is an arc style and square is a rectangular style. One thing to note is that only one current path can exist in the canvas drawing context at the same time. In order to draw different line segments, beginPath()
must be called before each drawing to clear the current route and start a new path.
Let's try using different lineJoin
values to draw the styles at the focus of the two line segments.
ctx.lineWidth = 20;ctx.textAlign = 'center';ctx.lineCap = 'butt';let colors = ['red', 'green', 'blue'];let lineJoins = ['bevel', 'round' , 'miter'];for (let [index, lj] of lineJoins.entries()) { ctx.strokeStyle = colors[index]; //Set the color of the line segment ctx.lineJoin = lj; //Set lineJoin ctx.beginPath(); //Clear the current path ctx.moveTo(10 + 80 * index, 20); ctx.lineTo(50 + 80 * index, 20); ctx.lineTo(50 + 80 * index, 60); ctx.stroke(); ctx.fillText(lj, 40 + 80 * index, 80);}
It can be seen that the three types lineJoin
are different in processing the focus of the two line segments. Among them, when setting lineJoin=miter
, the maximum ratio of the length of the miter line to half the line width can be set by setting the miterLimit
attribute. When this ratio is exceeded, lineJoin
will adopt the bevel method.
Canvas can not only draw solid lines, but also dotted lines. Draw a dotted line by setting the lineDashOffset
property and calling setLineDash()
.
ctx.lineWidth = 10;ctx.textAlign = 'center';ctx.setLineDash([8, 8]); //Represents 8 pixels in the solid line part and 8 pixels in the gap part let colors = ['red', 'green ', 'blue'];let lineDashOffsets = [1, 2, 4];for (let [index, ldOffset] of lineDashOffsets.entries()) { ctx.strokeStyle = colors[index]; //Line segment color ctx.lineDashOffset = ldOffset; //The offset is set ctx.beginPath(); ctx.moveTo(10, 20 + 20 * index); ctx.lineTo( 100, 20 + 20 * index); ctx.stroke(); ctx.fillText(`lineDashOffset:${ldOffset}`, 160, 25 + 20 * index);}
As you can see from the picture, lineDashOffset
is the offset set to start drawing the dotted line. The setLineDash()
method accepts an array parameter. If the number of arrays is an odd number, it will copy the current array element by default to make it an even number. From the 0th element, it represents the length of the solid line part, the 1st element represents the length of the gap part, the 2nd element represents the length of the solid line part, the 3rd element represents the length of the gap part, if it reaches the last element of the array , it will start from scratch again, and so on.
ctx.lineWidth = 10;ctx.textAlign = 'center';let colors = ['red', 'green', 'blue', 'gray'];let lineDashes = [[20, 20], [40, 40] , [20, 40], [20, 40, 20]];for (let [index, ld] of lineDashes.entries()) { ctx.strokeStyle = colors[index]; //Set color ctx.setLineDash(ld); //Set lineDash ctx.beginPath(); ctx.moveTo(10, 20 + 20 * index); ctx.lineTo(171, 20 + 20 * index); ctx.stroke(); ctx.fillText(`lineDashes:[${ld}]`, 240, 25 + 20 * index);}
let lineDashOffset = 0; //Initial lineDashOffsetctx.strokeStyle = 'green';function animate() { if (lineDashOffset > 25) { lineDashOffset = 0; } ctx.clearRect(0, 0, width, height); //Clear the current canvas ctx.lineDashOffset = -lineDashOffset; //Set lineDashOffset ctx.setLineDash([4, 4]); //Set the length of the solid line and the length of the gap ctx.rect(20, 20, 100, 100); //Draw a rectangle ctx.stroke(); //Add the current path to the canvas Stroke lineDashOffset += 1; //lineDashOffset offset plus 1 window.requestAnimationFrame(animate); //Use the browser frame rate to repeatedly execute the animate function}animate();summary
When drawing a line segment, you must understand the concept of the current path of the canvas. At a certain moment, there is only one current path in the canvas. When starting a new path, beginPath()
must be called. You can set the drawing style of line segments by setting lineWidth
, lineCap
, and lineJoin
. When stroking a line segment, you can set the color of the line segment through strokeStyle
.
Not only solid lines can be drawn in canvas, but also dashed lines can be drawn through lineDashOffset
and setLineDash()
.
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.