-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvue.js
100 lines (91 loc) · 2.24 KB
/
vue.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
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
96
97
98
99
100
new Vue({
el: '#app',
data: {
canvasTop: 0,
canvasLeft: 0,
startX: 0,
startY: 0,
lineWidth: 10,
isDrawing: false,
isEraser: false,
selectedColor: '#000000',
colors: [
'#000000',
'#FFDD57',
'#4286f4',
'#23d160',
'#FF8600',
'#ff3860',
],
},
computed: {
cursorStyle() {
return {
width: `${this.lineWidth}px`,
height: `${this.lineWidth}px`,
background: this.selectedColor,
};
}
},
methods: {
draw(e) {
if (!this.isDrawing) {
return;
}
const {canvas, ctx} = this.getCanvas();
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = this.selectedColor;
ctx.lineWidth = this.lineWidth;
ctx.beginPath();
// start from
ctx.moveTo(this.startX, this.startY);
// go to
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
// 1. Update start point to where mouse is unpressed
// Otherwise it'd be always 0,0
[this.startX, this.startY] = [e.offsetX, e.offsetY]
},
onMouseDown(e) {
this.isDrawing = true;
// 2. set the drawing point to where the mouse down is pressed
[this.startX, this.startY] = [e.offsetX, e.offsetY]
},
onMouseMove(e) {
this.draw(e);
const x = e.offsetX + this.canvasLeft;
const y = e.offsetY + this.canvasTop;
const cursor = this.$refs.cursor;
cursor.style.transform = `translate(${x - 10}px, ${y - 10}px)`;
},
onMouseUp() {
this.isDrawing = false;
},
onMouseOut() {
this.isDrawing = false;
},
onMouseEnter() {
const {canvas} = this.getCanvas();
[this.canvasTop, this.canvasLeft] = [canvas.offsetTop, canvas.offsetLeft]
},
selectColor(color) {
this.selectedColor = color;
this.isEraser = false;
},
selectEraser() {
this.selectedColor = '#FFFFFF';
this.isEraser = true;
},
selectTrash() {
this.isEraser = false;
const {canvas, ctx} = this.getCanvas();
ctx.clearRect(0, 0, canvas.width, canvas.height);
},
getCanvas() {
const canvas = this.$refs.myCanvas;
const ctx = canvas.getContext('2d');
return { canvas, ctx };
},
},
})