Home  >  Article  >  Web Front-end  >  How to draw dotted lines using Canvas

How to draw dotted lines using Canvas

PHP中文网
PHP中文网Original
2017-06-22 15:27:563603browse

We mentioned in the previous chapter that the drawing of linear paths mainly uses methods such as movoTo() and lineTo(). Of course, the Canvas 2D API also provides a dotted line drawing method, CanvasRenderingContext2D.setLineDash();

Let’s take a look at how to draw a dotted line

Syntax

ctx.setLineDash(segments);

Parameter segments:

An Array array.

A set of numbers describing the length of alternately drawn line segments and gaps (coordinate space units).

If the number of array elements is an odd number, the array elements will be copied and repeated. For example, [5, 15, 25] becomes [5, 15, 25, 5, 15, 25].

Maybe we didn’t understand the last sentence here, it doesn’t matter, let’s continue reading.

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();
}

So drawing a dotted line is also very simple. Let’s try to change the parameters of the setLineDash() method. See what the difference is in the results

= 4= 'green'50, 60400, 60= 4= 'red'0, 100400, 100


We can see from this example 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 a few 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 the examples above that the setLineDash() method is based on The elements in the parameter are grouped between "segments and intervals" and then looped to draw the dashed line.

But in the second example, the number of elements of the parameter we passed in is a base number, which looks a little different from when the parameter elements are an even number. It will copy the elements and repeat them,

This is what we said at the beginning. If the number of parameter segment elements is an odd number, the elements of the array will be copied and repeated. [10, 20, 30] will become [10, 20, 30, 10, 20, 30].

getLineDash method


There is a setLineDash method to set it The corresponding method is to obtain the line segments and spacing of the dotted line.

ctx.getLineDash()

This method returns an Array array. A set of numbers that describe the length of alternately drawn line segments and gaps (in coordinate space units). If the number of array elements is odd, the array elements are copied and repeated. For example, setting the line segment to [5, 15, 25] will result in the following return value [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]

Extend CanvasRenderingContext2D Draw dotted line

Not only can we use the canvas API to draw dotted lines, we can also extend a method to draw dotted lines ourselves.
Extension ideas:
1. Get the starting point coordinates
2. Calculate the total length of the dotted line, calculate how many short lines the dotted line contains and then loop Drawing

Without further ado, let’s go directly to the code

var canvas = document.getElementById('canvas');var cxt = canvas.getContext('2d');var moveToFunction = CanvasRenderingContext2D.prototype.moveTo;
CanvasRenderingContext2D.prototype.moveToLocation = {};// 重新定义moveTo方法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 = 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' : 'lineTo'](startX + (deltaX/numberDash)*i, startY + (deltaY/numberDash)*i); //等同于this.moveTo(x, y)或者 this.LineTo(x, y)    }this.moveTo(x, y); //连续绘制虚线时,起点从当前点开始};//绘制虚线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:

We can draw a dotted line through the setLineDash() method , this method will perform loop drawing with the number of elements in the parameter being group, but please note that the number of elements passed in to the method is the number of elements in the parameter.

We can also customize and expand the method of drawing dotted lines, which mainly involves obtaining the starting point and then calculating the number of line segments for loop drawing

Drawing graphics on canvas Interested students, please continue to pay attention to subsequent updates. If there is something wrong, please point it out and communicate more.

If you need to reprint, please indicate the source, thank you very much!

The above is the detailed content of How to draw dotted lines using Canvas. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn