使用canvas画一个简单的开机动画

在前端开发中,使用HTML的<canvas>元素可以创建复杂的图形和动画。下面是一个简单的开机动画示例,它使用canvas绘制一个逐渐加载的圆环来模拟开机过程:

  1. 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; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #000; }
        canvas { border: 1px solid white; }
    </style>
</head>
<body>
    <canvas id="loadingCanvas" width="200" height="200"></canvas>
    <script src="script.js"></script>
</body>
</html>
  1. JavaScript代码 (script.js文件):
const canvas = document.getElementById('loadingCanvas');
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 70;
let startAngle = -0.5 * Math.PI; // 开始角度设置为-90度(即竖直向上方向)
let endAngle = startAngle; // 结束角度初始与开始角度相同
const animationDuration = 2000; // 动画持续时间(毫秒)
const increment = 0.02; // 每次动画增加的弧度值(控制动画速度)
let animationStartTime = null; // 动画开始时间

function animate() {
    if (!animationStartTime) animationStartTime = Date.now(); // 记录动画开始时间
    const elapsedTime = Date.now() - animationStartTime; // 计算已过去的时间
    const progress = Math.min(elapsedTime / animationDuration, 1); // 计算动画进度(0到1之间)
    endAngle = startAngle + progress * 2 * Math.PI; // 根据进度计算结束角度
    drawCircle(startAngle, endAngle); // 绘制圆环
    if (progress < 1) { // 如果动画还未完成,则继续动画
        requestAnimationFrame(animate); // 使用requestAnimationFrame实现平滑动画效果
    }
}

function drawCircle(start, end) {
    ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除之前的绘制内容
    ctx.beginPath(); // 开始新的路径绘制
    ctx.arc(centerX, centerY, radius, start, end, false); // 绘制圆弧路径(不闭合)
    ctx.lineWidth = 10; // 设置线条宽度
    ctx.strokeStyle = '#0f0'; // 设置线条颜色(绿色)
    ctx.stroke(); // 描边绘制圆弧路径(不显示填充)
}

animate(); // 开始动画效果

这段代码创建了一个逐渐加载的圆环动画,模拟了开机时的加载效果。你可以根据需要调整圆环的大小、颜色、动画速度等参数来定制自己的开机动画。

posted @ 2024-12-29 06:18  王铁柱6  阅读(54)  评论(0)    收藏  举报