forked from webmachinelearning/webnn-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pen.js
57 lines (51 loc) · 1.39 KB
/
pen.js
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
'use stricit';
export class Pen {
constructor(cavans) {
this.canvas = cavans;
this.canvas.style.backgroundColor = 'black';
this.canvas.style.cursor = 'crosshair';
this.context = cavans.getContext('2d');
this.down = false;
this.isCleared = false;
this.start = {};
const self = this;
this.canvas.addEventListener('mousedown', (e) => {
self.down = true;
self.start = self.getPosition(e);
});
this.canvas.addEventListener('mouseup', (e) => {
self.down = false;
});
this.canvas.addEventListener('mousemove', (e) => {
if (self.down) {
const end = self.getPosition(e);
self.draw(self.start, end);
self.start = end;
}
});
}
getPosition(e) {
const rect = this.canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
return {x: x, y: y};
}
draw(start, end) {
this.isCleared = false;
this.context.strokeStyle = 'white';
this.context.lineJoin = 'round';
this.context.lineWidth = 20;
this.context.beginPath();
this.context.moveTo(start.x, start.y);
this.context.lineTo(end.x, end.y);
this.context.closePath();
this.context.stroke();
}
setIsCleared(isCleared) {
this.isCleared = isCleared;
}
clear() {
this.isCleared = true;
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}