Canvas learning Summary 3: Draw dotted lines and canvas dotted lines

Source: Internet
Author: User

Canvas learning Summary 3: Draw dotted lines and canvas dotted lines

As mentioned in the previous chapter, linear path rendering mainly uses movoTo () and lineTo () methods. Of course, the Canvas 2D API also provides the dotted line rendering method, CanvasRenderingContext2D. setLineDash ();

Next let's take a look at the method of drawing the dotted line.

 

Syntax

ctx.setLineDash(segments);

Parameter segments:

An Array.

A set of numbers that describe the length of a line segment and spacing (unit of coordinate space) alternately.

If the number of elements in the array is odd, the elements in the array are duplicated. For example, [5, 15, 25] is changed to [5, 15, 25, 5, 15, 25].

The last sentence here may not be clear. It doesn't matter. Let's continue.

 

Let's draw a simple dotted line first.

 

function drawDashed(){  cxt.lineWidth = 4;  cxt.strokeStyle = 'green';  cxt.beginPath();  cxt.setLineDash([5, 15]);  cxt.moveTo(20, 20);  cxt.lineTo(400, 20);  cxt.stroke();}

 

Therefore, it is very easy to draw the dotted line. We try to change the parameters of the setLineDash () method to see if the results are different.

function drawDashed(){
  cxt.lineWidth = 4; cxt.strokeStyle = 'green'; cxt.beginPath(); cxt.setLineDash([5]); cxt.moveTo(0, 60); cxt.lineTo(400, 60); cxt.stroke(); cxt.lineWidth = 4; cxt.strokeStyle = 'red'; cxt.beginPath(); cxt.setLineDash([]); cxt.moveTo(0, 100); cxt.lineTo(400, 100);
  cxt.stroke();
}

 


From this example, we can see that when our parameter array has only one element, our "line segment and interval" are equal. When the element of the parameter array is empty, we draw a solid line.

 

Let's look at several examples.

 

function drawDashed(){    cxt.lineWidth = 4;    cxt.strokeStyle = 'blue';    cxt.beginPath();    cxt.setLineDash([20, 5]);    cxt.moveTo(20, 40);    cxt.lineTo(380, 40);    cxt.stroke();    cxt.strokeStyle = 'green';    cxt.beginPath();    cxt.setLineDash([10, 20, 30]);    cxt.moveTo(20, 80);    cxt.lineTo(380, 80);    cxt.stroke();    cxt.strokeStyle = 'red';    cxt.beginPath();    cxt.setLineDash([10, 20, 30, 40]);    cxt.moveTo(20, 120);    cxt.lineTo(380, 120);    cxt.stroke();}

 

 

 

We can see from several examples that the setLineDash () method forms a group between "line segments and intervals" based on the elements in the parameter, then loops and draws a dotted line.

However, in the second example, the number of elements of the input parameter is the base number. It looks a little different from that of the Parameter Element when it is an even number. It will copy and repeat the elements,

This is what we started to call. If the number of segments elements is an odd number, the elements of the array will be copied and repeated. [10, 20, 30] is changed to [10, 20, 30, 10, 20, 30].

 

GetLineDash Method


The setLineDash method is used to set the line and spacing of the dotted line. The corresponding method is to obtain the line and spacing of the dotted line.

ctx.getLineDash()

 

This method returns an Array. A set of numbers that describe the length of a line segment and spacing (unit of coordinate space) alternately. If the number of array elements is odd, the array elements are copied and repeated. For example, if a line segment is set to [5, 15, 25], the following return values are [5, 15, 25, 5, 15, 25].

var canvas = document.getElementById("canvas");var ctx = canvas.getContext("2d");ctx.setLineDash([5, 15]);ctx.beginPath();ctx.moveTo(0,100);ctx.lineTo(400, 100);ctx.stroke();
console.log(ctx.getLineDash()); // [5, 15]

 

 

Expand CanvasRenderingContext2D to draw the dotted line

We can not only use the canvas API to draw the dotted line, but also expand a method to draw the dotted line by ourselves.
Expansion ideas:
1. Get the start Coordinate
2. Calculate the total length of the dotted line, calculate the number of short lines contained in the dotted line, and draw them cyclically.

Let's talk about the code.

Var canvas = document. getElementById ('canvas '); var cxt = canvas. getContext ('2d '); var moveToFunction = CanvasRenderingContext2D. prototype. moveTo; CanvasRenderingContext2D. prototype. moveToLocation ={}; // redefine the moveTo method CanvasRenderingContext2D. prototype. moveTo = function (x, y) {this. moveToLocation. x = x; this. moveToLocation. y = y; moveToFunction. apply (this, [x, y]) ;}; CanvasRenderingContext2D. prototype. DashedLineTo = function (x, y, dashedLength) {dashedLength = undefined? 5: dashedLength; var startX = this. moveToLocation. x; var startY = this. moveToLocation. y; var deltaX = x-startX; var deltaY = y-startY; var numberDash = Math. floor (Math. sqrt (deltaX * deltaX + deltaY * deltaY)/dashedLength); for (var I = 0; I <numberDash; I ++) {this [I % 2 = 0? 'Moveto ': 'line'] (startX + (deltaX/numberDash) * I, startY + (deltaY/numberDash) * I); // equivalent to this. moveTo (x, y) or this. lineTo (x, y)} this. moveTo (x, y); // when the dotted line is continuously drawn, the starting point starts from the current point}; // draw the dotted line cxt. lineWidth = 3; cxt. strokeStyle = 'green'; cxt. moveTo (20, 20); cxt. dashedLineTo (200,200); cxt. dashedLineTo (300,100, 10); cxt. dashedLineTo (400,300); cxt. stroke ();

 

 

Summary:

You can use the setLineDash () method to draw the dotted line. This method uses the number of parameters as a group to draw the line cyclically. However, you must note that the input method is the number of parameters.

We can also customize the method to draw the dotted line, which is mainly to obtain the starting point and calculate the number of line segments to draw them cyclically.

If you are interested in drawing a canvas image, please keep an eye on the subsequent updates. If there is anything wrong, please point out and share more information.

If you need to reprint the data, please specify the source. Thank you very much!

Related Article

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.