js实现摆针


以下是使用JavaScript实现摆针动画的几种方法,涵盖基础实现和优化方案:
使用Canvas绘制摆针动画
const canvas = document.getElementById('pendulumCanvas');
const ctx = canvas.getContext('2d');
const width = canvas.width = 400;
const height = canvas.height = 400;
const pivotX = width / 2;
const pivotY = height / 4;
const rodLength = 150;
const bobRadius = 20;
let angle = Math.PI / 4;
let angularVelocity = 0;
const damping = 0.995;
const gravity = 0.5;
function update() {
const angularAcceleration = -gravity / rodLength * Math.sin(angle);
angularVelocity += angularAcceleration;
angularVelocity *= damping;
angle += angularVelocity;
}
function draw() {
ctx.clearRect(0, 0, width, height);
const bobX = pivotX + rodLength * Math.sin(angle);
const bobY = pivotY + rodLength * Math.cos(angle);
ctx.beginPath();
ctx.moveTo(pivotX, pivotY);
ctx.lineTo(bobX, bobY);
ctx.strokeStyle = '#333';
ctx.lineWidth = 3;
ctx.stroke();
ctx.beginPath();
ctx.arc(bobX, bobY, bobRadius, 0, Math.PI * 2);
ctx.fillStyle = '#c00';
ctx.fill();
ctx.stroke();
}
function animate() {
update();
draw();
requestAnimationFrame(animate);
}
animate();
使用CSS动画模拟摆针
<style>
.pendulum {
position: relative;
width: 2px;
height: 200px;
background: #333;
margin: 0 auto;
transform-origin: top center;
animation: swing 2s ease-in-out infinite alternate;
}
.bob {
position: absolute;
bottom: -20px;
left: -18px;
width: 40px;
height: 40px;
border-radius: 50%;
background: #c00;
}
@keyframes swing {
0% { transform: rotate(30deg); }
100% { transform: rotate(-30deg); }
}
</style>
<div class="pendulum">
<div class="bob"></div>
</div>
使用物理引擎实现精确模拟(如matter.js)
const engine = Matter.Engine.create();
const render = Matter.Render.create({
element: document.body,
engine: engine,
options: {
width: 800,
height: 600,
wireframes: false
}
});
const pendulum = Matter.Composites.stack(400, 100, 1, 1, 0, 0, function() {
return Matter.Bodies.circle(0, 0, 20, {
restitution: 0.8,
friction: 0.005
});
});
Matter.Composite.add(pendulum, Matter.Constraint.create({
pointA: { x: 400, y: 100 },
bodyB: pendulum.bodies[0],
length: 200,
stiffness: 0.05
}));
Matter.Composite.add(engine.world, pendulum);
Matter.Engine.run(engine);
Matter.Render.run(render);
优化建议
- 添加鼠标交互功能允许用户拖动摆针
- 实现多摆针系统展示混沌效应
- 添加能量损耗参数使摆动逐渐停止
- 使用WebGL(如Three.js)实现3D摆针效果
以上方法可根据需求选择,Canvas方案最适合需要精确物理模拟的场景,CSS方案适合简单UI动画,物理引擎方案适合复杂交互系统。






