基于js的重力模拟研究

基于js的重力模拟研究

YQYStudio(一个为人民服务的公仆) 略有小成

第一部分为在线调试代码,第二部分为重力算法代码块。

代码调试器
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>在线 HTML 代码运行程序</title>
<style>
body {
display: flex;
margin: 0;
height: 100vh;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* 左边输入区域 */
#input-area {
flex: 9;
padding: 20px;
background-color: #f4f4f9;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1) inset;
}

#code-input {
width: 100%;
height: 100%;
resize: none;
font-family: monospace;
border: 1px solid #ccc;
border-radius: 4px;
padding: 10px;
box-sizing: border-box;
}

/* 右边功能区 */
#function-area {
flex: 2;
padding: 20px;
background-color: #e8e8f3;
display: flex;
flex-direction: column;
box-shadow: -2px 0 5px rgba(0, 0, 0, 0.1);
}

button {
margin-bottom: 10px;
padding: 10px;
border: none;
border-radius: 4px;
background-color: #007BFF;
color: white;
cursor: pointer;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
transition: background-color 0.3s ease;
}

button:hover {
background-color: #0056b3;
}

/* 模态框样式 */
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
justify-content: center;
align-items: center;
}

.modal-content {
background-color: white;
border-radius: 4px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
position: relative;
min-width: 300px;
min-height: 200px;
width: 80%;
height: 80%;
}

.modal-header {
padding: 10px;
background-color: #f0f0f0;
cursor: move;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid #ccc;
}

.close {
font-size: 28px;
font-weight: bold;
cursor: pointer;
}

.close:hover {
color: red;
}

.modal-body {
padding: 10px;
height: calc(100% - 41px);
}

.modal-body iframe {
width: 100%;
height: 100%;
border: none;
}

/* 调整大小的边框样式 */
.resizer {
position: absolute;
}

.resizer.right {
right: 0;
top: 0;
height: 100%;
width: 5px;
cursor: ew-resize;
}

.resizer.bottom {
bottom: 0;
left: 0;
width: 100%;
height: 5px;
cursor: ns-resize;
}

.resizer.bottom-right {
right: 0;
bottom: 0;
width: 10px;
height: 10px;
cursor: nwse-resize;
}
</style>
</head>

<body>
<!-- 左边输入区域 -->
<div id="input-area">
<textarea id="code-input" placeholder="请输入 HTML 代码"></textarea>
</div>
<!-- 右边功能区 -->
<div id="function-area">
<button id="run-code">运行代码</button>
<button id="copy-code">复制代码</button>
</div>
<!-- 模态框 -->
<div id="modal" class="modal">
<div class="modal-content">
<div class="modal-header">
<span>运行结果</span>
<span class="close">&times;</span>
</div>
<div class="modal-body">
<iframe id="result"></iframe>
</div>
<div class="resizer right"></div>
<div class="resizer bottom"></div>
<div class="resizer bottom-right"></div>
</div>
</div>

<script>
const codeInput = document.getElementById('code-input');
const runCodeButton = document.getElementById('run-code');
const copyCodeButton = document.getElementById('copy-code');
const resultFrame = document.getElementById('result');
const modal = document.getElementById('modal');
const closeBtn = document.querySelector('.close');

// 运行代码功能
runCodeButton.addEventListener('click', () => {
const code = codeInput.value;
modal.style.display = 'flex';
const doc = resultFrame.contentDocument || resultFrame.contentWindow.document;
doc.open();
doc.write(code);
doc.close();
});

// 复制代码功能
copyCodeButton.addEventListener('click', () => {
codeInput.select();
document.execCommand('copy');
alert('代码已复制到剪贴板');
});

// 关闭模态框
closeBtn.addEventListener('click', () => {
modal.style.display = 'none';
});

// 点击模态框外部关闭模态框
window.addEventListener('click', (event) => {
if (event.target === modal) {
modal.style.display = 'none';
}
});

// 模态框拖动功能
const modalHeader = document.querySelector('.modal-header');
let isDragging = false;
let offsetX, offsetY;

modalHeader.addEventListener('mousedown', (e) => {
isDragging = true;
const content = modal.querySelector('.modal-content');
offsetX = e.clientX - content.getBoundingClientRect().left;
offsetY = e.clientY - content.getBoundingClientRect().top;
e.preventDefault();
});

document.addEventListener('mousemove', (e) => {
if (isDragging) {
const content = modal.querySelector('.modal-content');
content.style.left = (e.clientX - offsetX) + 'px';
content.style.top = (e.clientY - offsetY) + 'px';
}
});

document.addEventListener('mouseup', () => {
isDragging = false;
});

// 模态框调整大小功能
const resizers = document.querySelectorAll('.resizer');
let currentResizer;

resizers.forEach((resizer) => {
resizer.addEventListener('mousedown', (e) => {
currentResizer = resizer;
isDragging = true;
offsetX = e.clientX;
offsetY = e.clientY;
e.preventDefault();
});
});

document.addEventListener('mousemove', (e) => {
if (isDragging && currentResizer) {
const content = modal.querySelector('.modal-content');
const rect = content.getBoundingClientRect();

if (currentResizer.classList.contains('right')) {
content.style.width = Math.max(300, rect.width + (e.clientX - offsetX)) + 'px';
offsetX = e.clientX;
} else if (currentResizer.classList.contains('bottom')) {
content.style.height = Math.max(200, rect.height + (e.clientY - offsetY)) + 'px';
offsetY = e.clientY;
} else if (currentResizer.classList.contains('bottom-right')) {
content.style.width = Math.max(300, rect.width + (e.clientX - offsetX)) + 'px';
content.style.height = Math.max(200, rect.height + (e.clientY - offsetY)) + 'px';
offsetX = e.clientX;
offsetY = e.clientY;
}
}
});

document.addEventListener('mouseup', () => {
isDragging = false;
currentResizer = null;
});

// 阻止模态框内点击触发关闭事件
const modalContent = document.querySelector('.modal-content');
modalContent.addEventListener('click', (e) => {
e.stopPropagation();
});
</script>
</body>

</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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>小球重力动画(优化版)</title>
<style>
body {
display: flex;
margin: 0;
height: 100vh;
background-color: #121212;
color: white;
}

#animation-container {
flex: 9;
background-color: #1e1e1e;
position: relative;
overflow: hidden;
}

#control-panel {
flex: 2;
background-color: #262626;
padding: 20px;
}

.ball {
position: absolute;
border-radius: 50%;
left: 0;
top: 0;
}

.wind-effect {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: repeating-linear-gradient(
45deg,
rgba(255, 255, 255, 0.1),
rgba(255, 255, 255, 0.1) 5px,
transparent 5px,
transparent 10px
);
opacity: 0;
transition: opacity 1s ease-in-out;
}
</style>
</head>

<body>
<div id="animation-container"></div>
<div id="control-panel">
<button id="add-ball">增加小球数量</button>
<button id="start-animation">开始动画</button>
<button id="pause-animation">暂停动画</button>
<button id="increase-speed">提高小球运动速度</button>
<button id="clear-balls">清除小球</button>
<button id="simulate-wind">模拟自然风</button>
<button id="clear-wind">清除自然风</button>
<button id="reset-animation">重置动画</button>
</div>

<script>
const animationContainer = document.getElementById('animation-container');
const balls = [];
let isPaused = true;
let gravity = 0.1;
let speedMultiplier = 1;
let animationFrameId;
let windStrength = 0;
let windEffect;
const collisionEnergyLoss = 0.9; // 碰撞能量损耗因子

// 缓存容器尺寸
let containerWidth = animationContainer.offsetWidth;
let containerHeight = animationContainer.offsetHeight;

// 响应窗口大小变化
window.addEventListener('resize', () => {
containerWidth = animationContainer.offsetWidth;
containerHeight = animationContainer.offsetHeight;
});

function createBall() {
const ball = document.createElement('div');
ball.className = 'ball';
const size = Math.random() * 20 + 10;
const initialX = Math.random() * (containerWidth - size);
const initialY = 0;

Object.assign(ball.style, {
width: `${size}px`,
height: `${size}px`,
backgroundColor: `rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`,
transform: `translate(${initialX}px, ${initialY}px)`
});

animationContainer.appendChild(ball);

balls.push({
element: ball,
x: initialX,
y: initialY,
vx: (Math.random() - 0.5) * 2 * speedMultiplier,
vy: 0,
size: size
});
}

function checkCollision(ball1, ball2) {
const dx = ball2.x - ball1.x;
const dy = ball2.y - ball1.y;
const distance = Math.sqrt(dx * dx + dy * dy);
return distance < (ball1.size + ball2.size) / 2;
}

function handleCollision(ball1, ball2) {
const dx = ball2.x - ball1.x;
const dy = ball2.y - ball1.y;
const distance = Math.sqrt(dx * dx + dy * dy);
const normalX = dx / distance;
const normalY = dy / distance;

const v1n = ball1.vx * normalX + ball1.vy * normalY;
const v2n = ball2.vx * normalX + ball2.vy * normalY;
const v1t = ball1.vx - v1n * normalX;
const v2t = ball2.vx - v2n * normalX;

const m1 = ball1.size;
const m2 = ball2.size;

const v1nNew = (v1n * (m1 - m2) + 2 * m2 * v2n) / (m1 + m2);
const v2nNew = (v2n * (m2 - m1) + 2 * m1 * v1n) / (m1 + m2);

// 应用能量损耗
ball1.vx = (v1t + v1nNew * normalX) * collisionEnergyLoss;
ball1.vy = (v1t + v1nNew * normalY) * collisionEnergyLoss;
ball2.vx = (v2t + v2nNew * normalX) * collisionEnergyLoss;
ball2.vy = (v2t + v2nNew * normalY) * collisionEnergyLoss;

// 将小球稍微分开,避免重叠
const overlap = (ball1.size + ball2.size) / 2 - distance;
ball1.x -= overlap * 0.5 * normalX;
ball1.y -= overlap * 0.5 * normalY;
ball2.x += overlap * 0.5 * normalX;
ball2.y += overlap * 0.5 * normalY;
}

function updatePhysics() {
for (let i = balls.length - 1; i >= 0; i--) {
const ball = balls[i];
ball.vx += windStrength * speedMultiplier;
ball.vy += gravity * speedMultiplier;
ball.x += ball.vx;
ball.y += ball.vy;

if (ball.x < 0) {
ball.x = 0;
ball.vx = -ball.vx;
} else if (ball.x > containerWidth - ball.size) {
ball.x = containerWidth - ball.size;
ball.vx = -ball.vx;
}

if (ball.y > containerHeight - ball.size) {
ball.y = containerHeight - ball.size;
ball.vy = -ball.vy * 0.8;
if (Math.abs(ball.vy) < 0.5) {
ball.vy = 0;
}
}

ball.element.style.transform = `translate(${ball.x}px, ${ball.y}px)`;
}

for (let i = 0; i < balls.length; i++) {
for (let j = i + 1; j < balls.length; j++) {
if (checkCollision(balls[i], balls[j])) {
handleCollision(balls[i], balls[j]);
}
}
}
}

function animate() {
if (!isPaused) {
updatePhysics();
}
animationFrameId = requestAnimationFrame(animate);
}

function clearBalls() {
while (balls.length > 0) {
const ball = balls.pop();
animationContainer.removeChild(ball.element);
}
}

function simulateWind() {
windStrength = (Math.random() - 0.5) * 0.2;

if (!windEffect) {
windEffect = document.createElement('div');
windEffect.className = 'wind-effect';
animationContainer.appendChild(windEffect);
}

windEffect.style.opacity = 1;

setTimeout(() => {
windEffect.style.opacity = 0;
}, 3000);
}

function clearWind() {
windStrength = 0;
if (windEffect) {
windEffect.style.opacity = 0;
}
}

function resetAnimation() {
clearBalls();
clearWind();
isPaused = true;
speedMultiplier = 1;
if (windEffect) {
animationContainer.removeChild(windEffect);
windEffect = null;
}
createBall();
isPaused = false;
}

document.getElementById('add-ball').addEventListener('click', createBall);
document.getElementById('start-animation').addEventListener('click', () => {
if (isPaused) {
isPaused = false;
if (!animationFrameId) animate();
}
});
document.getElementById('pause-animation').addEventListener('click', () => {
isPaused = true;
});
document.getElementById('increase-speed').addEventListener('click', () => {
speedMultiplier = Math.min(speedMultiplier * 1.2, 5);
});
document.getElementById('clear-balls').addEventListener('click', clearBalls);
document.getElementById('simulate-wind').addEventListener('click', simulateWind);
document.getElementById('clear-wind').addEventListener('click', clearWind);
document.getElementById('reset-animation').addEventListener('click', resetAnimation);

createBall();
animate();
</script>
</body>

</html>
  • 标题: 基于js的重力模拟研究
  • 作者: YQYStudio(一个为人民服务的公仆)
  • 创建于 : 2025-02-09 22:48:23
  • 更新于 : 2025-09-09 22:53:10
  • 链接: https://yqystudio-github-io.pages.dev/2025/02/09/基于js的重力模拟研究/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
目录
基于js的重力模拟研究