Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to draw Line segments through canvas in html

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how to draw line segments through canvas in html". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Basic knowledge

Canvas basic knowledge is not much, mainly master how to draw line segments, graphics, pictures, text and so on. Canvas can be drawn in a browser, or you can use node-canvas to draw simple pictures on the node server. This article only records how to draw in the browser, as for how to draw on the node side, you can check the relevant information.

When you draw in a browser, you first define the canvas element in html. The default width and height is 300x150, 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, which will be discussed later.

The current browser does not support canvas, please upgrade your browser

Before drawing, we need to get the 2d rendering context context of the current canvas, and then always draw by manipulating context.

Let canvas = document.querySelector ('# canvas'); if (! canvas) {throw new Error ('can not find canvas element');} / / Note 2d. The parameter must be lowercase; / / you can get the 3D drawing context let ctx = canvas.getContext ('2d') by setting the parameter to webgl

Note: the above code snippet will be ignored in the subsequent example, and the ctx variable will be used directly to represent the 2d drawing context of canvas.

Let's take a look at the coordinate system in canvas 2d drawing. At present, the upper left corner of the canvas element is the coordinate origin (0Power0), the horizontal right is the positive direction of the X axis, and the vertical downward is the positive direction of the Y axis, as shown in the following figure. You can manipulate the coordinate system and achieve some animation by translating (translate), rotating (rotate), and zooming (scale). This part will be explained in detail in the animation knowledge section.

Line segment

When drawing a simple line segment, we usually first set the line segment style, such as color, line width, line end 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, and so on. The following code simply draws a red line with a width of 10 from (10) to (50) 60.

Ctx.strokeStyle = 'red';ctx.lineWidth = 10 * * ctx.moveto (10,10); ctx.lineTo (50,60); ctx.stroke ()

First take a look at the methods and properties related to drawing line segments

Related attributes:

LineCap, which tells the browser how to draw the end of the segment. The optional value is one of three: butt,round,square. The default is butt.

LineWidth, which determines the pixel width of the segment. Must be non-negative, non-infinite, default is 1.0.

LineJoin, which determines how the focus is drawn when two segments intersect, and takes effect only if the two segments are in different directions. Available value: bevel,round,miter. The default value is miter.

MiterLimit, which tells the browser how to draw the focus of line segments in the form of miter. Only if lineJoin='miter' is valid, the default is 10.0.

LineDashOffset, sets the dotted line offset, which defaults to 0.0.

Related methods:

BeginPath, which resets the current path by clearing all subpaths in the current path. It is usually called first when drawing a closed graph.

ClosePath, which shows a closed path. This method is used to close arc paths and open paths created by curves or line segments.

MoveTo, moves the current drawing point to the specified coordinates.

LineTo, draw a line segment from the previous point to the specified coordinate point.

SetLineDash, the method used to set dashed lines, and the parameter is an array indicating the length of the drawn solid lines and the length of the gap between the solid lines.

Try to draw the same segment by setting different lineCap values.

Ctx.lineWidth = 10 for 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 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 above figure, setting lineCap to round and square will add endpoints of a certain length to both ends of the original segment, except that round is an arc style and square is a rectangle style. It is important to note that only one current path can exist at a time in the context of canvas drawing. In order to draw different line segments, you must call beginPath () before each drawing to clear the current route and start a new path.

Let's try to draw the style at the focus of two segments with different lineJoin values.

Ctx.lineWidth = 20tx.textAlign = 'center';ctx.lineCap =' butt';let colors = ['red',' green', 'blue']; let lineJoins = [' bevel', 'round',' miter']; for (let [index, textAlign] of lineJoins.entries ()) {ctx.strokeStyle = colors [index]; / / set the color of the 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);}

You can see the difference between the three lineJoin in dealing with the focus of the two segments. When setting the lineJoin= "miter", you can set the maximum ratio of the length of the miter to the line width of two-thirds by setting the miterLimit property. When this ratio is exceeded, the lineJoin will adopt the bevel mode.

Canvas can draw not only solid lines but also dashed lines. Draw a dotted line by setting the lineDashOffset property and calling setLineDash ().

Ctx.lineWidth = 10 index ctx.textAlign = 'center';ctx.setLineDash ([8,8]); / / indicates 8 pixels of solid line and 8 pixels of gap let colors = [' red', 'green',' blue']; let lineDashOffsets = [1,2,4]; for (let [index, textAlign] of lineDashOffsets.entries ()) {ctx.strokeStyle = colors [index]; / / segment color ctx.lineDashOffset = ldOffset / set offset ctx.beginPath (); ctx.moveTo (10,20 + 20 * index); ctx.lineTo (100,20 + 20 * index); ctx.stroke (); ctx.fillText (`lineDashOffset:$ {ldOffset} `, 160,25 + 20 * index);}

You can see from the figure that lineDashOffset is the offset set to start drawing dotted lines. The setLineDash () method accepts an array parameter, and if the number of the array is odd, it makes an even copy of the current array element by default. From the 0th element, it represents the length of the solid part, the first element represents the length of the gap part, the second element represents the length of the solid part, and the third element represents the length of the gap part. If it comes to the last element of the array, it will start from scratch, and so on.

Ctx.lineWidth = 10 index ctx.textAlign = 'center';let colors = [' red', 'green',' blue', 'gray']; let lineDashes = [[20,20], [40,40], [20,40], [20,40,20]]; for (let [index, textAlign] 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 current canvas ctx.lineDashOffset =-lineDashOffset; / / set lineDashOffset ctx.setLineDash ([4,4]); / / set solid line length and gap length ctx.rect (20,20,100,100); / / draw a rectangular ctx.stroke () / / A pair of canvas current path strokes lineDashOffset + = 1; / lineDashOffset offset plus 1 window.requestAnimationFrame (animate); / / use browser frame rate to repeatedly execute the animate function} animate (); "how to draw line segments through canvas in html" is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report