h5实现小车
使用HTML5实现小车动画
HTML5结合CSS3和JavaScript可以实现简单的小车动画效果。以下是一个基础的实现方法:
HTML结构
<div class="road">
<div class="car">
<div class="body"></div>
<div class="wheel front-wheel"></div>
<div class="wheel back-wheel"></div>
</div>
</div>
CSS样式

.road {
width: 100%;
height: 100px;
background: #555;
position: relative;
overflow: hidden;
}
.car {
position: absolute;
bottom: 20px;
left: 0;
width: 120px;
height: 60px;
}
.body {
width: 100%;
height: 40px;
background: #3498db;
border-radius: 15px 15px 0 0;
}
.wheel {
position: absolute;
width: 30px;
height: 30px;
background: #333;
border-radius: 50%;
bottom: -15px;
}
.front-wheel {
right: 10px;
}
.back-wheel {
left: 10px;
}
JavaScript动画
let car = document.querySelector('.car');
let position = 0;
function animateCar() {
position += 2;
if(position > window.innerWidth) {
position = -120;
}
car.style.left = position + 'px';
requestAnimationFrame(animateCar);
}
animateCar();
使用Canvas实现更复杂的小车
对于更复杂的图形和动画效果,可以使用HTML5 Canvas:

<canvas id="carCanvas" width="800" height="200"></canvas>
const canvas = document.getElementById('carCanvas');
const ctx = canvas.getContext('2d');
let x = 0;
function drawCar(xPos) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 车身
ctx.fillStyle = '#e74c3c';
ctx.fillRect(xPos, 100, 120, 40);
// 车窗
ctx.fillStyle = '#3498db';
ctx.fillRect(xPos + 80, 105, 30, 20);
// 车轮
ctx.fillStyle = '#2c3e50';
ctx.beginPath();
ctx.arc(xPos + 30, 140, 15, 0, Math.PI * 2);
ctx.fill();
ctx.beginPath();
ctx.arc(xPos + 90, 140, 15, 0, Math.PI * 2);
ctx.fill();
}
function animate() {
x += 2;
if(x > canvas.width) x = -120;
drawCar(x);
requestAnimationFrame(animate);
}
animate();
添加交互控制
可以通过键盘事件让用户控制小车移动:
let carSpeed = 0;
document.addEventListener('keydown', (e) => {
if(e.key === 'ArrowRight') carSpeed = 5;
if(e.key === 'ArrowLeft') carSpeed = -5;
});
document.addEventListener('keyup', () => {
carSpeed = 0;
});
function animate() {
x += carSpeed;
if(x > canvas.width) x = -120;
if(x < -120) x = canvas.width;
drawCar(x);
requestAnimationFrame(animate);
}
使用CSS动画实现简单移动
如果不需要复杂交互,纯CSS也能实现小车移动:
.car {
animation: drive 5s linear infinite;
}
@keyframes drive {
from { transform: translateX(-120px); }
to { transform: translateX(100vw); }
}
这些方法展示了从简单到相对复杂的HTML5小车实现方式,可以根据需求选择适合的方案。
