-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLine.js
More file actions
95 lines (85 loc) · 2.44 KB
/
Line.js
File metadata and controls
95 lines (85 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import CanvasElement from '../core/CanvasElement';
import {checkOptions, RedrawProperties} from '../core/util';
@RedrawProperties([
'x1', 'x2', 'y1', 'y2',
'color', 'lineCap', 'dashed',
'dashSpacing', 'thickness'
])
class Line extends CanvasElement {
constructor(options){
super(options);
checkOptions(options, ['x1','y1', 'x2', 'y2']);
this.x1 = options.x1;
this.y1 = options.y1;
this.x2 = options.x2;
this.y2 = options.y2;
this.color = options.color || '#000';
this.lineCap = options.lineCap || 'square';
this.dashed = options.dashed || false;
this.dashSpacing = options.dashSpacing || [10,5];
this.thickness = options.thickness || 1;
}
draw(){
if(this.dashed){
this._drawDashedLine();
} else {
this._drawRegularLine();
}
}
_drawRegularLine(){
this.canvas.beginPath();
this.canvas.lineWidth = this.thickness;
this.canvas.strokeStyle = this.color;
this.canvas.lineCap = this.lineCap;
this.canvas.moveTo(this.x1, this.y1);
this.canvas.lineTo(this.x2, this.y2);
this.canvas.stroke();
}
_drawDashedLine(){
this._dashedLine(this.x1, this.y1, this.x2, this.y2, this.dashSpacing);
}
//Draw a dashed line onto the current context.
//http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
// this.param x {Number} start x position
// this.param y {Number} start y position
// this.param x2 {Number} end x position
// this.param y2 {Number} end y position
// this.param da {Array} an array of two values. The first value is how long of a dash to draw,
// the second is how much space before the next dash.
_dashedLine(x, y, x2, y2, da){
if(!da){
da = [10,5];
}
this.canvas.save();
const dx = (x2-x);
const dy = (y2-y);
const len = Math.sqrt(dx*dx + dy*dy);
const rot = Math.atan2(dy, dx);
this.canvas.strokeStyle = this.color;
this.canvas.lineCap = this.lineCap;
this.canvas.lineWidth = this.thickness;
this.canvas.translate(x, y);
this.canvas.moveTo(0, 0);
this.canvas.rotate(rot);
this.canvas.beginPath();
const dc = da.length;
let di = 0;
let draw = true;
x = 0;
while (len > x){
x += da[di++ % dc];
if (x > len){
x = len;
}
if(draw){
this.canvas.lineTo(x, 0);
} else {
this.canvas.moveTo(x, 0);
}
draw = !draw;
}
this.canvas.stroke();
this.canvas.restore();
}
}
export default Line;