-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathdanmu.html
106 lines (94 loc) · 3.11 KB
/
danmu.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<title>Danmaku Display</title>
<style>
body {
margin: 0;
padding: 0;
background-color: transparent;
overflow: hidden;
}
#danmu-container {
position: relative;
width: 100%;
height: 100vh;
background-color: transparent;
color: white;
overflow: hidden;
pointer-events: none;
}
.danmu {
position: absolute;
white-space: nowrap;
font-size: 18px;
}
</style>
</head>
<body>
<div id="danmu-container"></div>
<script>
const danmuContainer = document.getElementById('danmu-container');
const socket = new WebSocket('ws://{{hostname}}/dy-dm');
const maxRows = 5;
let currentRow = 0;
const rowHeight = 30;
const minDuration = 3; // 最小动画持续时间,单位为秒
// 随机生成颜色的函数
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function moveDanmu(danmuElement, duration) {
const start = performance.now();
const startX = window.innerWidth;
const endX = -danmuElement.offsetWidth;
const interval = 1000 / 60; // 60fps
const move = () => {
const now = performance.now();
const elapsed = now - start;
if (elapsed < duration) {
const progress = elapsed / duration;
const x = startX - (startX - endX) * progress;
danmuElement.style.left = x + 'px';
requestAnimationFrame(move);
} else {
danmuContainer.removeChild(danmuElement);
}
};
requestAnimationFrame(move);
}
socket.onmessage = function (event) {
const danmuData = JSON.parse(event.data);
danmuData.forEach(danmu => {
const danmuElement = document.createElement('div');
danmuElement.textContent = danmu.text;
danmuElement.className = 'danmu';
// 设置随机颜色
danmuElement.style.color = getRandomColor();
danmuContainer.appendChild(danmuElement);
const y = currentRow * rowHeight;
danmuElement.style.top = y + 'px';
const textLength = danmu.text.length;
const baseSpeed = 0.2;
let animationDuration = textLength * baseSpeed;
if (animationDuration < minDuration) {
animationDuration = minDuration;
}
moveDanmu(danmuElement, animationDuration * 1000);
// 循环设置行
currentRow = (currentRow + 1) % maxRows;
});
};
socket.onerror = function (error) {
console.error('WebSocket error:', error);
};
</script>
</body>
</html>