效果演示

html 代码
<!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 {margin: 0;overflow: hidden;background-color: #f0f0f0;}
canvas {display: block;}
</style>
</head>
<body>
<canvas id="stage"></canvas>
<script>
const canvas = document.getElementById('stage');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const stickman = {x: canvas.width / 2,y: canvas.height / 2,width: 5,height: 100,bodyAngle: 0,leftArmAngle: 0,rightArmAngle: 0,leftLegAngle: 0,rightLegAngle: 0,speed: 0.02 };
function drawStickman(x, y, bodyAngle, leftArmAngle, rightArmAngle, leftLegAngle, rightLegAngle) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(x, y);
ctx.rotate(bodyAngle);
ctx.beginPath();
ctx.arc(0, -stickman.height / 2, 20, 0, Math.PI * 2);
ctx.fillStyle = "#000";
ctx.fill();
ctx.fillStyle = "#3498db";
ctx.fillRect(-25, -stickman.height / 2 + 20, 50, 40);
ctx.beginPath();
ctx.moveTo(0, -stickman.height / 2 + 20);
ctx.lineTo(0, stickman.height / 2);
ctx.lineWidth = stickman.width;
ctx.strokeStyle = "#000";
ctx.stroke();
ctx.save();
ctx.rotate(leftArmAngle);
ctx.beginPath();
ctx.moveTo(0, -stickman.height / 2 + 30);
ctx.lineTo(-stickman.height / 2, 0);
ctx.lineWidth = 5;
ctx.strokeStyle = "#000";
ctx.stroke();
ctx.restore();
ctx.save();
ctx.rotate(rightArmAngle);
ctx.beginPath();
ctx.moveTo(0, -stickman.height / 2 + 30);
ctx.lineTo(stickman.height / 2, 0);
ctx.lineWidth = 5;
ctx.strokeStyle = "#000";
ctx.stroke();
ctx.restore();
ctx.fillStyle = "#2ecc71";
ctx.fillRect(-15, stickman.height / 2 - 10, 30, 40);
ctx.save();
ctx.rotate(leftLegAngle);
ctx.beginPath();
ctx.moveTo(0, stickman.height / 2);
ctx.lineTo(-stickman.height / 4, stickman.height / 2 + 50);
ctx.lineWidth = 5;
ctx.strokeStyle = "#000";
ctx.stroke();ctx.restore();ctx.save();ctx.rotate(rightLegAngle); ctx.beginPath();ctx.moveTo(0, stickman.height / 2);ctx.lineTo(stickman.height / 4, stickman.height / 2 + 50);ctx.lineWidth = 5;ctx.strokeStyle = "#000";ctx.stroke();ctx.restore();ctx.restore();
}
function animate() {
const time = Date.now() * stickman.speed;
stickman.bodyAngle = Math.sin(time) * 0.2;
stickman.leftArmAngle = Math.sin(time) * 0.8;
stickman.rightArmAngle = Math.cos(time) * 0.8;
stickman.leftLegAngle = Math.sin(time) * 0.4;
stickman.rightLegAngle = Math.cos(time) * 0.4;
drawStickman(stickman.x, stickman.y, stickman.bodyAngle, stickman.leftArmAngle, stickman.rightArmAngle, stickman.leftLegAngle, stickman.rightLegAngle);
requestAnimationFrame(animate);}
animate();
</script>
</body>
</html>