How to draw segments using canvas

Source: Internet
Author: User
Tags dashed line linecap node server
This article is about how to draw segments with canvas, and then we'll look at specific content and hopefully help you.

To learn canvas, first you need to know how to draw line segments, and then through a lot of simple lines to achieve more complex graphics, such as common chart, histogram, line chart, etc. are through a segment of the line to achieve.

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 a simple picture can be drawn on the node server with Node-canvas. This article is only recorded in the browser drawing, as to how to draw on the node side, you can go to view the relevant information.

Drawing in the browser, first define the canvas element in the HTML, the default width height is 300 * 150, can be passed width and height set. Note that the canvas element style is wide and the canvas is wider than it is a thing, this piece will be said later.

<canvas id= "Canvas" >  <p> the current browser does not support canvas, please upgrade your browser </p></canvas>

Before we draw, we need to get the current canvas's 2d draw context, which is always drawn by manipulating the context.

Let canvas = Document.queryselector (' #canvas '), if (!canvas) {  throw new Error (' Can not find canvas element ');} Note 2d. The parameter must be lowercase;//By setting the parameter to WebGL, you can get the 3d drawing context let CTX = Canvas.getcontext (' 2d ');

Note: The preceding code snippet is ignored in the following example, and the variable is used to ctx represent the 2d drawing context of the canvas.

Then look at the coordinate system in canvas 2d drawing, the top left corner of the current canvas element is the coordinate origin (0,0), the horizontal right is the x-axis positive direction, and the vertical downward is the y-axis positive direction, such as. You can manipulate the coordinate system by panning (translate), rotation (rotate), scaling (scale) to achieve some animation, which is explained in detail in the Animation knowledge section.

Segment

When drawing a simple line segment, it is common to first set the style of the line segment, such as color, line width, line end style, etc., we set strokeStyle to set ctx the global drawing style, can be a rgba valid 16 binary color value, or gradient object, etc. The following code simply draws a red line from (10,10) to (50,60), with a width of 10.

Ctx.strokestyle = ' red '; ctx.linewidth = 10;ctx.moveto (ten); Ctx.lineto (); Ctx.stroke ();

First look at the methods and properties associated with drawing segments,

Related properties:

    • LineCap, which tells the browser how to draw the endpoint of a segment, with an optional value of one of the following three: Butt,round,square. The default is butt.

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

    • LineJoin, determines how the focus is drawn when the two segments intersect, only if the two segments are not in the same direction. Desirable value: Bevel,round,miter. The default value is miter.

    • Miterlimit, tells the browser how to draw the Miter form of the segment focus, only if lineJoin='miter' it is valid, the default is 10.0.

    • Linedashoffset, sets the dash offset, which defaults to 0.0.

Related methods:

    • Beginpath to reset the current path by clearing all the sub-paths in the current path. It is generally called first when drawing a closed drawing.

    • Closepath, which shows the enclosing path of a segment. This method is used to close the ARC path and the open path created by the curve or segment.

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

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

    • Setlinedash, the method used to set the dashed line, which is an array that indicates the length of the drawing solid, and the length of the gap between the solid lines.

Try setting different lineCap values to draw the same 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 segment  CTX.LINECAP = LC;//Set LineCap  Ctx.beginpath ();//clear the current path  Ctx.moveto (ten, + * index);  Ctx.lineto (+ + * index);  Ctx.stroke ();  Ctx.filltext (LC, +, + * index);}

As can be seen from the results, lineCap when set to round and Square , the ends of the original segment are added to the end of a certain length, but the round is the arc style,Square is a rectangular style. It is important to note that there can only be one current path at the same time in the canvas drawing context, in order to draw different segments, it must be called before each draw beginPath() to clear the current route and start a new path.

Try different lineJoin values to draw the style at the focus of the two segments

Ctx.linewidth = 20;ctx.textalign = ' center '; ctx.linecap = ' butt '; let colors = [' red ', ' green ', ' blue '];let linejoins = [' b Evel ', ' round ', ' miter '];for (let [index, LJ] 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 (+ + * index);  Ctx.lineto (+ + * index);  Ctx.lineto (+ + * index,);  Ctx.stroke ();  Ctx.filltext (LJ, + + * index, 80);}

As you can see, the three types lineJoin differ in the focus of processing two line segments. When set, the lineJoin="miter" maximum ratio of the length of the miter line to the One-second-wire width can be set by setting the property, and miterLimit when this ratio is exceeded, the lineJoin bevel method is used.

Canvas can not only draw solid lines, but also draw dashed lines. Draws a dashed line by setting lineDashOffset properties and calling setLineDash() methods.

Ctx.linewidth = 10;ctx.textalign = ' center '; Ctx.setlinedash ([8, 8]); Represents a solid portion of 8 pixels, the gap portion 8 pixels let colors = [' red ', ' green ', ' blue '];let linedashoffsets = [1, 2, 4];for (let [index, Ldoffset] of L Inedashoffsets.entries ()) {  Ctx.strokestyle = Colors[index];//Segment color  ctx.linedashoffset = ldoffset;//Offset set  Ctx.beginpath ();  Ctx.moveto (Ten, + * index);  Ctx.lineto (+ + * index);  Ctx.stroke ();  Ctx.filltext (' Linedashoffset:${ldoffset} ', + + * index);}

As you can see from the diagram lineDashOffset is the offset of the set start drawing dashed line. setLineDash()method, which accepts an array parameter, if the number of arrays is odd, the current array element is copied by default to make even. From the No. 0 element, representing the solid part length, the 1th element, representing the gap part length, the 2nd element, representing the solid part length, the 3rd element, representing the gap part length, if the last element of the array, will start from scratch, and so on.

Ctx.linewidth = 10;ctx.textalign = ' center '; let colors = [' red ', ' green ', ' blue ', ' gray '];let linedashes = [[20, 20], [40, [+], [+], [+], 20]];for (let [index, LD] of linedashes.entries ()) {  Ctx.strokestyle = Colors[index];//Set color C1/>ctx.setlinedash (LD); Set Linedash  Ctx.beginpath ();  Ctx.moveto (Ten, + * index);  Ctx.lineto (171, + * index);  Ctx.stroke ();  Ctx.filltext (' linedashes:[${ld}] ', + + * index);}

The ant line can be implemented by dynamic setting lineDashOffset , such as selecting an ant line in the edge of the selection in PS.

Let Linedashoffset = 0; Initial Linedashoffsetctx.strokestyle = ' green '; function animate () {  if (Linedashoffset >) {    linedashoffset = 0;  }  Ctx.clearrect (0, 0, width, height); Empty the current canvas  ctx.linedashoffset =-linedashoffset;//Set Linedashoffset  Ctx.setlinedash ([4, 4]);// Set solid length and gap length  ctx.rect (20, 20, 100, 100);//Draw a rectangle  ctx.stroke ();//Stroke The current path of the canvas  linedashoffset + = 1; Linedashoffset offset plus 1  window.requestanimationframe (animate);//Use the browser frame rate to perform the Animate function}animate () repeatedly;

Summary

To understand the canvas's current path concept when drawing segments, there is only one current path in the canvas at a time, which must be called when a new path is started beginPath() . You can set lineWidth the lineCap lineJoin drawing style for a segment by setting it. When you stroke a segment, you can strokeStyle set the color of the segment.

Not only can you draw solid lines in the canvas, but you can also lineDashOffset setLineDash() draw dashed lines by and.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.