用html和js 写一个跳舞的火柴人
时间: 2023-12-24 10:05:50 浏览: 41
以下是一个简单的跳舞的火柴人的HTML和JS代码:
HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Dancing Stickman</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="stickman.js"></script>
</body>
</html>
```
JS代码:
```js
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 定义火柴人的身体部分
const stickman = {
head: {
x: canvas.width / 2,
y: 100,
radius: 20
},
body: {
x1: canvas.width / 2,
y1: 120,
x2: canvas.width / 2,
y2: 200
},
leftArm: {
x1: canvas.width / 2,
y1: 140,
x2: canvas.width / 2 - 40,
y2: 160
},
rightArm: {
x1: canvas.width / 2,
y1: 140,
x2: canvas.width / 2 + 40,
y2: 160
},
leftLeg: {
x1: canvas.width / 2,
y1: 200,
x2: canvas.width / 2 - 20,
y2: 280
},
rightLeg: {
x1: canvas.width / 2,
y1: 200,
x2: canvas.width / 2 + 20,
y2: 280
}
}
// 绘制火柴人
function drawStickman() {
// 绘制头部
ctx.beginPath();
ctx.arc(stickman.head.x, stickman.head.y, stickman.head.radius, 0, 2 * Math.PI);
ctx.stroke();
// 绘制身体
ctx.beginPath();
ctx.moveTo(stickman.body.x1, stickman.body.y1);
ctx.lineTo(stickman.body.x2, stickman.body.y2);
ctx.stroke();
// 绘制左臂
ctx.beginPath();
ctx.moveTo(stickman.leftArm.x1, stickman.leftArm.y1);
ctx.lineTo(stickman.leftArm.x2, stickman.leftArm.y2);
ctx.stroke();
// 绘制右臂
ctx.beginPath();
ctx.moveTo(stickman.rightArm.x1, stickman.rightArm.y1);
ctx.lineTo(stickman.rightArm.x2, stickman.rightArm.y2);
ctx.stroke();
// 绘制左腿
ctx.beginPath();
ctx.moveTo(stickman.leftLeg.x1, stickman.leftLeg.y1);
ctx.lineTo(stickman.leftLeg.x2, stickman.leftLeg.y2);
ctx.stroke();
// 绘制右腿
ctx.beginPath();
ctx.moveTo(stickman.rightLeg.x1, stickman.rightLeg.y1);
ctx.lineTo(stickman.rightLeg.x2, stickman.rightLeg.y2);
ctx.stroke();
}
// 改变火柴人的姿势
function changePose() {
// 改变左臂和右腿的位置
stickman.leftArm.x1 -= 5;
stickman.leftArm.x2 -= 5;
stickman.rightLeg.x1 -= 5;
stickman.rightLeg.x2 -= 5;
// 改变右臂和左腿的位置
stickman.rightArm.x1 += 5;
stickman.rightArm.x2 += 5;
stickman.leftLeg.x1 += 5;
stickman.leftLeg.x2 += 5;
// 绘制新的火柴人姿势
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawStickman();
}
// 每隔100毫秒改变一次姿势
setInterval(changePose, 100);
// 绘制初始的火柴人姿势
drawStickman();
```
这个跳舞的火柴人会每隔100毫秒改变一次姿势,看起来像在跳舞。你可以根据自己的需求和喜好调整火柴人的姿势和动作。