-
Notifications
You must be signed in to change notification settings - Fork 0
/
drawing.js
116 lines (81 loc) · 2.85 KB
/
drawing.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
const BACKGROUND_COLOUR = '#000000';
const LINE_COLOUR = '#FFFFFF';
const LINE_WIDTH = 15;
var currentX = 0;
var currentY = 0;
var previousX = 0;
var previousY = 0;
var canvas;
var context;
function prepareCanvas() {
//console.log('Preparing Canvas');
// Connectong the canvas to the canvas we specified in index.html
canvas = document.getElementById('my-canvas');
context = canvas.getContext('2d');
context.fillStyle = BACKGROUND_COLOUR;
context.fillRect(0, 0, canvas.clientWidth, canvas.clientHeight);
context.strokeStyle = LINE_COLOUR;
context.lineWidth = LINE_WIDTH;
context.lineJoin = 'round';
var isPainting = false;
// Next line- basically when mouse down- all the code in the function gets executed
document.addEventListener('mousedown', function (event) {
//console.log('Mouse Pressed!');
isPainting = true;
currentX = event.clientX - canvas.offsetLeft;
currentY = event.clientY - canvas.offsetTop;
});
document.addEventListener('mousemove', function (event) {
if (isPainting) {
previousX = currentX;
currentX = event.clientX - canvas.offsetLeft;
previousY = currentY;
currentY = event.clientY - canvas.offsetTop;
draw();
}
});
document.addEventListener('mouseup', function (event) {
//console.log('Mouse Released');
isPainting = false;
});
canvas.addEventListener('mouseleave', function (event) {
isPainting = false;
});
// Touch Events- Optimizing for mobile
canvas.addEventListener('touchstart', function (event) {
//console.log('Touchdown!');
isPainting = true;
// This touvhes[0] represents the first touch
currentX = event.touches[0].clientX - canvas.offsetLeft;
currentY = event.touches[0].clientY - canvas.offsetTop;
});
canvas.addEventListener('touchend', function (event) {
isPainting = false;
});
canvas.addEventListener('touchcancel', function (event) {
isPainting = false;
});
canvas.addEventListener('touchmove', function (event) {
if (isPainting) {
previousX = currentX;
currentX = event.touches[0].clientX - canvas.offsetLeft;
previousY = currentY;
currentY = event.touches[0].clientY - canvas.offsetTop;
draw();
}
});
}
function draw() {
context.beginPath();
context.moveTo(previousX, previousY);
context.lineTo(currentX, currentY);
context.closePath();
context.stroke();
}
function clearCanvas() {
currentX = 0;
currentY = 0;
previousX = 0;
previousY = 0;
context.fillRect(0, 0, canvas.clientWidth, canvas.clientHeight);
}