-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
82 lines (70 loc) · 2.08 KB
/
script.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
let highestZ = 1;
class Paper {
holdingPaper = false;
rotating = false;
mouseTouchX = 0;
mouseTouchY = 0;
currX = 0;
currY = 0;
prevX = 0;
prevY = 0;
velocityX = 0;
velocityY = 0;
rotation = Math.random() * 25 - 15;
currentPaperX = 0;
currentPaperY = 0;
init(paper) {
document.addEventListener('mousemove', (e) => {
if(!this.rotating) {
this.currX = e.clientX;
this.currY = e.clientY;
this.velocityX = this.currX - this.prevX;
this.velocityY = this.currY - this.prevY;
}
const dirX = e.clientX - this.mouseTouchX;
const dirY = e.clientY - this.mouseTouchY;
const dirLength = Math.sqrt(dirX*dirX+dirY*dirY);
const dirNormalizedX = dirX / dirLength;
const dirNormalizedY = dirY / dirLength;
const angle = Math.atan2(dirNormalizedY, dirNormalizedX);
let degrees = 175 * angle / Math.PI;
degrees = (360 + Math.round(degrees)) % 360;
if(this.rotating) {
this.rotation = degrees;
}
if(this.holdingPaper) {
if(!this.rotating) {
this.currentPaperX += this.velocityX;
this.currentPaperY += this.velocityY;
}
this.prevX = this.currX;
this.prevY = this.currY;
paper.style.transform = `translateX(${this.currentPaperX}px) translateY(${this.currentPaperY}px) rotateZ(${this.rotation}deg)`;
}
})
paper.addEventListener('mousedown', (e) => {
if(this.holdingPaper) return;
this.holdingPaper = true;
paper.style.zIndex = highestZ;
highestZ += 1;
if(e.button === 0) {
this.mouseTouchX = this.currX;
this.mouseTouchY = this.currY;
this.prevX = this.currX;
this.prevY = this.currY;
}
if(e.button === 2) {
this.rotating = true;
}
});
window.addEventListener('mouseup', () => {
this.holdingPaper = false;
this.rotating = false;
});
}
}
const papers = Array.from(document.querySelectorAll('.paper'));
papers.forEach(paper => {
const p = new Paper();
p.init(paper);
});