要使用JavaScript实现简单的轨迹动画,你需要理解几个基础概念:
requestAnimationFrame
来创建一个动画循环,在每一帧中更新物体的位置并重新绘制路径。以下是一个简单的轨迹动画示例,其中一个小球沿着预定义的路径移动:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>轨迹动画示例</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
let x = 50; // 初始x坐标
let y = 50; // 初始y坐标
const speed = 2; // 移动速度
const path = [
{x: 50, y: 50},
{x: 200, y: 100},
{x: 400, y: 50},
{x: 200, y: 300},
{x: 50, y: 50}
]; // 定义轨迹点
let currentPathIndex = 0; // 当前路径点的索引
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, 10, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
}
function drawPath() {
ctx.beginPath();
ctx.moveTo(path[0].x, path[0].y);
for (let i = 1; i < path.length; i++) {
ctx.lineTo(path[i].x, path[i].y);
}
ctx.stroke();
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布
drawPath(); // 绘制路径
drawBall(); // 绘制小球
// 更新小球位置
const targetX = path[currentPathIndex].x;
const targetY = path[currentPathIndex].y;
x += (targetX - x) / speed;
y += (targetY - y) / speed;
// 检查是否到达当前路径点
if (Math.abs(x - targetX) < 1 && Math.abs(y - targetY) < 1) {
currentPathIndex++;
if (currentPathIndex >= path.length) {
currentPathIndex = 0; // 循环路径
}
}
requestAnimationFrame(animate); // 请求下一帧动画
}
animate(); // 开始动画
</script>
</body>
</html>
requestAnimationFrame
有助于优化动画性能,减少资源消耗。通过以上步骤和代码示例,你可以实现一个简单的轨迹动画。如果遇到具体问题,可以根据上述解决方法进行调试。
领取专属 10元无门槛券
手把手带您无忧上云