-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustom.js
90 lines (75 loc) · 2.21 KB
/
custom.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
window.onload = function(){
window.alert('Use arrow keys to draw. Press Shake button to restart!')
}
const canvas = document.getElementById('etch-a-sketch');
const context = canvas.getContext('2d');
const shakeButton = document.querySelector('.shake');
// Use 'destructuring' by making variables from a property on an object
// const width = canvas.width;
// const height = canvas.height;
const { width, height } = canvas;
// Generate random starting points using canvas w and h
let x = Math.floor(Math.random() * width);
let y = Math.floor(Math.random() * height);
context.lineJoin = 'round';
context.lineCap = 'round';
context.lineWidth = 10;
// Start the first drawing dot
context.beginPath();
context.moveTo(x,y);
context.lineTo(x,y);
context.stroke();
// Use object destructuring to take properties and rename them into propert variables so they are shorter
// Use options object as key variable in top-level.
function draw({key}){
context.beginPath();
context.moveTo(x,y);
switch (key){
case 'ArrowUp' :
y = y - 10;
break;
case 'ArrowDown' :
y = y + 10;
break;
case 'ArrowRight' :
x = x + 10;
break;
case 'ArrowLeft' :
x = x - 10;
break;
// switch statement needs default
default:
break;
}
// if (key == 'ArrowUp'){
// y = y - 10;
// } else if (key == 'ArrowDown'){
// x = x - 10;
// };
context.lineTo(x,y);
context.stroke();
}
function handleKey(e){
// Look for ArrowUp or ArrowDown
if (e.key.includes('Arrow')){
e.preventDefault();
console.log('Handling key');
console.log(e.key);
// Use Objects from the options in Line 26.
draw({key: e.key});
}
}
function clearCanvas(){
canvas.classList.add('shake');
canvas.addEventListener('animationend', function(){
navigator.vibrate(100);
console.log('Done the shake');
canvas.classList.remove('shake');
},
// Another argument for addeventlistener
{ once: true }
);
context.clearRect(0,0, width, height);
}
window.addEventListener('keydown', handleKey);
shakeButton.addEventListener('click', clearCanvas);