-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathetch-a-sketch.js
More file actions
64 lines (55 loc) · 1.54 KB
/
etch-a-sketch.js
File metadata and controls
64 lines (55 loc) · 1.54 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
// select elements on page (canvas)
const canvas = document.getElementById('etch-a-sketch');
const ctx = canvas.getContext('2d');
const shakebutton = document.querySelector('.shake')
// set up canvas for drawing
const MOVE_AMOUNT = 10;
const { width, height } = canvas;
let x = Math.floor(Math.random() * width);
let y = Math.floor(Math.random() * height);
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.lineWidth = 10;
// write a draw function
let hue = 0;
ctx.strokeStyle = `hsl(100, 100%, 50%)`;
function draw({ key }) {
hue += 1;
ctx.strokeStyle = `hsl(${Math.random() * 360}, 100%, 50%)`;
console.log(key);
ctx.beginPath();
ctx.moveTo(x, y);
if (key == 'ArrowUp') {
y -= MOVE_AMOUNT;
} else if (key == 'ArrowDown') {
y += MOVE_AMOUNT;
} else if (key == 'ArrowRight') {
x += MOVE_AMOUNT;
} else {
x -= MOVE_AMOUNT;
}
ctx.lineTo(x, y);
ctx.stroke();
}
// write handler for keys
function handleKey(e) {
if (e.key.includes('Arrow')) {
e.preventDefault();
draw({key: e.key});
console.log(e.key);
console.log("HANDLING KEY");
}
}
window.addEventListener('keydown', handleKey);
// clear or shake function
function clearCanvas() {
canvas.classList.add('shake');
ctx.clearRect(0, 0, width, height);
canvas.addEventListener("animationend", function() {
console.log("Let's do the rumba!");
canvas.classList.remove('shake');
},
{ once: true }
);
}
shakebutton.addEventListener("click", clearCanvas);