在前端开发中,使用HTML的<canvas>
元素可以创建丰富的图形和动画。以下是一个简单的示例,展示如何使用canvas制作一个加载动画。
- HTML结构:
首先,在HTML文件中添加一个<canvas>
元素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Loading Animation with Canvas</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f5f5f5;
}
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="loadingCanvas" width="200" height="200"></canvas>
<script src="script.js"></script>
</body>
</html>
- JavaScript动画:
在script.js
文件中,添加以下JavaScript代码来创建动画。
const canvas = document.getElementById('loadingCanvas');
const ctx = canvas.getContext('2d');
let angle = 0;
const speed = 0.02;
const radius = 70;
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
function drawCircle(x, y, radius, color) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function animate() {
clearCanvas();
drawCircle(centerX, centerY, radius, 'rgba(0, 0, 0, 0.1)'); // 背景圆
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate(angle);
ctx.beginPath();
ctx.moveTo(0, -radius);
ctx.lineTo(0, -20); // 控制杆的长度
ctx.lineWidth = 20; // 控制杆的宽度
ctx.strokeStyle = '#3498db'; // 控制杆的颜色
ctx.stroke();
ctx.closePath();
ctx.restore();
angle += speed;
if (angle > Math.PI * 2) angle = 0; // 重置角度,以防动画过快导致数字问题
requestAnimationFrame(animate); // 循环动画
}
animate(); // 开始动画
这段代码创建了一个简单的加载动画,其中有一个旋转的控制杆在一个半透明的背景圆内旋转。你可以根据需要调整颜色、速度、半径等参数来定制动画的外观和行为。