使用canvas制作一个10秒倒计时特效

在HTML5中,canvas元素用于在网页上绘制图形。你可以使用JavaScript在其上进行绘图。以下是一个简单的示例,展示如何使用canvas和JavaScript制作一个10秒倒计时特效:

  1. 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>10秒倒计时特效</title>
    <style>
        canvas {
            border: 1px solid black;
            display: block;
            margin: 50px auto;
        }
    </style>
</head>
<body>
    <canvas id="countdownCanvas" width="300" height="100"></canvas>
    <script src="script.js"></script>
</body>
</html>
  1. JavaScript代码 (script.js 文件):

在JavaScript文件中,你将编写代码来更新canvas并显示倒计时。

const canvas = document.getElementById('countdownCanvas');
const ctx = canvas.getContext('2d');
const fontSize = 40;
let count = 10;

function drawCountdown() {
    ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布上的内容
    ctx.font = `${fontSize}px Arial`;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillStyle = 'red';
    ctx.fillText(count, canvas.width / 2, canvas.height / 2); // 在画布上绘制文本

    if (count > 0) {
        count--; // 减少计数
        setTimeout(drawCountdown, 1000); // 每秒更新一次画布
    } else {
        ctx.fillStyle = 'green';
        ctx.fillText('时间到!', canvas.width / 2, canvas.height / 2); // 当倒计时结束时显示“时间到!”
    }
}

drawCountdown(); // 开始倒计时

这段代码首先获取canvas元素和它的2D渲染上下文。然后,它定义了一个drawCountdown函数,该函数负责在canvas上绘制倒计时的当前秒数。使用setTimeout函数每秒调用一次drawCountdown函数,从而更新显示的秒数。当倒计时到达0时,它将显示“时间到!”的文本。最后,通过调用drawCountdown函数开始倒计时。

posted @ 2024-12-29 09:31  王铁柱6  阅读(57)  评论(0)    收藏  举报