下面是一个单个 HTML 文件示例,展示了两个小球在六边形内运动的动画。六边形边框垂直于地面(像车轮),小球在其中受到重力、摩擦力和弹力的作用。左边小球模拟地球重力,右边小球模拟月球重力。
动画用 Canvas 实现,物理模拟比较简化,重点体现重力差异和摩擦、弹力的效果。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>六边形内小球物理动画(地球 vs 月球)</title>
<style>
body {
margin: 0;
background: #222;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
color: #eee;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
canvas {
background: #111;
border: 1px solid #555;
margin: 0 20px;
}
.container {
display: flex;
flex-direction: row;
align-items: center;
}
.label {
text-align: center;
margin-top: 8px;
font-size: 14px;
}
.box {
display: flex;
flex-direction: column;
align-items: center;
}
</style>
</head>
<body>
<div class="container">
<div class="box">
<canvas id="earth" width="300" height="300"></canvas>
<div class="label">地球重力 (g=9.8 m/s²)</div>
</div>
<div class="box">
<canvas id="moon" width="300" height="300"></canvas>
<div class="label">月球重力 (g=1.62 m/s²)</div>
</div>
</div>
<script>
(() => {
const canvasEarth = document.getElementById('earth');
const ctxEarth = canvasEarth.getContext('2d');
const canvasMoon = document.getElementById('moon');
const ctxMoon = canvasMoon.getContext('2d');
const width = canvasEarth.width;
const height = canvasEarth.height;
// 六边形参数
const hexRadius = 120; // 六边形半径(顶点到中心距离)
const ballRadius = 12;
// 物理参数
// 重力加速度 (像素/s²,比例缩放)
// 这里用一个比例因子把真实重力映射到像素单位
const gravityScale = 200; // 1 m/s² = 200 px/s² (调节动画速度)
const gEarth = 9.8 * gravityScale;
const gMoon = 1.62 * gravityScale;
// 摩擦系数(简化为速度衰减)
const friction = 0.995;
// 弹力系数(碰撞反弹)
const restitution = 0.85;
// 六边形顶点计算(中心在canvas中心)
function getHexPoints(cx, cy, r) {
const points = [];
for (let i = 0; i < 6; i++) {
const angle = Math.PI / 2 + i * Math.PI / 3; // 使边垂直于地面
points.push({
x: cx + r * Math.cos(angle),
y: cy + r * Math.sin(angle),
});
}
return points;
}
// 判断点是否在六边形内(利用射线法)
function pointInPolygon(point, polygon) {
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const xi = polygon[i].x, yi = polygon[i].y;
const xj = polygon[j].x, yj = polygon[j].y;
const intersect = ((yi > point.y) !== (yj > point.y)) &&
(point.x < (xj - xi) * (point.y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
return inside;
}
// 计算点到线段的最短距离和最近点
function pointLineDistance(px, py, x1, y1, x2, y2) {
const A = px - x1;
const B = py - y1;
const C = x2 - x1;
const D = y2 - y1;
const dot = A * C + B * D;
const len_sq = C * C + D * D;
let param = -1;
if (len_sq !== 0) param = dot / len_sq;
let xx, yy;
if (param < 0) {
xx = x1;
yy = y1;
} else if (param > 1) {
xx = x2;
yy = y2;
} else {
xx = x1 + param * C;
yy = y1 + param * D;
}
const dx = px - xx;
const dy = py - yy;
return {distance: Math.sqrt(dx * dx + dy * dy), closestX: xx, closestY: yy};
}
// 小球类
class Ball {
constructor(cx, cy, radius, gravity) {
this.cx = cx;
this.cy = cy;
this.radius = radius;
this.gravity = gravity;
// 初始位置:六边形中心稍偏上
this.pos = {x: cx, y: cy - radius * 2};
this.vel = {x: 100, y: 0}; // 初始有水平速度,制造运动
this.acc = {x: 0, y: 0};
}
update(dt, hexPoints) {
// 重力方向:垂直向下(y轴正方向)
this.acc.x = 0;
this.acc.y = this.gravity;
// 速度更新
this.vel.x += this.acc.x * dt;
this.vel.y += this.acc.y * dt;
// 摩擦力简化为速度衰减
this.vel.x *= friction;
this.vel.y *= friction;
// 位置更新
this.pos.x += this.vel.x * dt;
this.pos.y += this.vel.y * dt;
// 碰撞检测和响应(与六边形边界)
for (let i = 0; i < 6; i++) {
const p1 = hexPoints[i];
const p2 = hexPoints[(i + 1) % 6];
const {distance, closestX, closestY} = pointLineDistance(this.pos.x, this.pos.y, p1.x, p1.y, p2.x, p2.y);
if (distance < this.radius) {
// 计算法线向量(从边界指向小球中心)
let nx = this.pos.x - closestX;
let ny = this.pos.y - closestY;
const len = Math.sqrt(nx * nx + ny * ny);
if (len === 0) continue; // 避免除0
nx /= len;
ny /= len;
// 投影速度到法线方向
const vDotN = this.vel.x * nx + this.vel.y * ny;
if (vDotN < 0) { // 只有当速度指向边界时才反弹
// 反弹速度
this.vel.x = this.vel.x - (1 + restitution) * vDotN * nx;
this.vel.y = this.vel.y - (1 + restitution) * vDotN * ny;
// 位置修正,防止穿透
const penetration = this.radius - distance;
this.pos.x += nx * penetration;
this.pos.y += ny * penetration;
}
}
}
}
draw(ctx) {
ctx.beginPath();
ctx.fillStyle = '#ffcc00';
ctx.shadowColor = '#ffaa00';
ctx.shadowBlur = 10;
ctx.arc(this.pos.x, this.pos.y, this.radius, 0, Math.PI * 2);
ctx.fill();
ctx.shadowBlur = 0;
}
}
// 绘制六边形
function drawHex(ctx, points) {
ctx.beginPath();
ctx.strokeStyle = '#0af';
ctx.lineWidth = 3;
ctx.shadowColor = '#0af';
ctx.shadowBlur = 10;
ctx.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++) {
ctx.lineTo(points[i].x, points[i].y);
}
ctx.closePath();
ctx.stroke();
ctx.shadowBlur = 0;
}
// 初始化两个小球
const centerX = width / 2;
const centerY = height / 2;
const hexPointsEarth = getHexPoints(centerX, centerY, hexRadius);
const hexPointsMoon = getHexPoints(centerX, centerY, hexRadius);
const ballEarth = new Ball(centerX, centerY, ballRadius, gEarth);
const ballMoon = new Ball(centerX, centerY, ballRadius, gMoon);
let lastTime = null;
function animate(time) {
if (!lastTime) lastTime = time;
const dt = (time - lastTime) / 1000; // 秒
lastTime = time;
// 清空画布
ctxEarth.clearRect(0, 0, width, height);
ctxMoon.clearRect(0, 0, width, height);
// 画六边形
drawHex(ctxEarth, hexPointsEarth);
drawHex(ctxMoon, hexPointsMoon);
// 更新小球
ballEarth.update(dt, hexPointsEarth);
ballMoon.update(dt, hexPointsMoon);
// 画小球
ballEarth.draw(ctxEarth);
ballMoon.draw(ctxMoon);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
})();
</script>
</body>
</html>
说明:
- 六边形顶点计算时,起始角度设为 90°,使六边形的边垂直于地面(即六边形的边是竖直的,像车轮)。
- 小球初始有一个水平速度,受重力加速度影响,运动轨迹会在六边形内反弹。
- 摩擦力通过速度乘以一个小于1的系数实现,模拟速度逐渐减小。
- 弹力系数控制碰撞反弹的能量损失。
- 左边画布模拟地球重力,右边画布模拟月球重力,重力加速度不同,运动效果明显不同。
你可以直接保存为 .html 文件,用浏览器打开即可看到动画效果。需要调整参数可以修改脚本中的常量。