-
Notifications
You must be signed in to change notification settings - Fork 1
/
roulette.js
116 lines (86 loc) · 3.14 KB
/
roulette.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 items = [
"http://demo.st-marron.info/roulette/sample/star.png",
"http://demo.st-marron.info/roulette/sample/flower.png",
"http://demo.st-marron.info/roulette/sample/coin.png",
"http://demo.st-marron.info/roulette/sample/mshroom.png",
"http://demo.st-marron.info/roulette/sample/chomp.png",
];
class Roulette {
constructor() {
this.SIZE = 128;
this.LENGTH = 80;
this.DURATION = 5000;
this.progress = 0;
this.startTime = 0;
this.lastItem = 0;
this.level = 0;
this.roulette = document.getElementById("roulette");
this.items = this.roulette.children;
}
init(images) {
if (!Array.isArray(images)) {
console.log("You need to pass images as an array!");
}
images.forEach(src => {
const img = new Image();
img.src = src;
});
for (let i = 0; i < 6; i++) {
const item = this.items[i];
item.style.position = 'absolute';
item.style.transform = `translateX(${i * this.SIZE}px)`;
item.lastChild.src = this.getItem();
}
}
start(lastItem) {
this.level = 0;
this.progress = 0;
this.lastItem = lastItem;
this.startTime = Date.now();
for (let i = 0; i < 6; i++) {
this.items[i].value = 0;
}
window.requestAnimationFrame(() => this.update());
}
update() {
this.progress = (Date.now() - this.startTime) / this.DURATION;
if (this.progress > 1) {
this.progress = 1;
this.render();
return;
}
this.render();
window.requestAnimationFrame(() => this.update());
}
render() {
const off = this.interpolator(this.progress) * this.SIZE * this.LENGTH;
const WIDTH = this.SIZE * 6;
for (let i = 0; i < 6; i++) {
const item = this.items[i];
const base = (i + 1) * this.SIZE - off;
const index = -Math.floor(base / WIDTH);
const value = ((base % WIDTH) + WIDTH) % WIDTH - this.SIZE;
item.style.transform = `translateX(${value}px)`;
if (item.value != index) {
this.level += index - item.value;
item.value = index;
item.lastChild.src = this.getItem();
if (this.level == this.LENGTH - 3) {
item.lastChild.src = this.getItem(this.lastItem);
}
}
}
}
interpolator(val) {
return Math.pow(Math.sin(val * Math.PI / 2), 2.6);
}
getItem(val) {
val = typeof val !== "undefined" ? val : Math.floor(Math.random() * items.length);
return items[val];
}
}
const roulette = new Roulette();
roulette.init(items);
const btnStart = document.getElementById("roulette-start");
const selectWinner = document.getElementById("roulette-select-winner");
btnStart.onclick = () => roulette.start(parseInt(selectWinner.value, 10)); // KYTIČKA