使用canvas制作一个环形进度条,中间带有数字
在前端开发中,使用HTML5的<canvas>元素来制作一个环形进度条以及在其中显示数字是一个有趣且实用的任务。以下是一个简单的示例,展示了如何创建一个基本的环形进度条,并在其中心显示进度百分比。
- 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>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="progressCanvas" width="200" height="200"></canvas>
<script src="script.js"></script>
</body>
</html>
- JavaScript代码 (
script.js):
const canvas = document.getElementById('progressCanvas');
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 70;
const lineWidth = 10;
let progress = 0.75; // 进度,范围从0到1
function drawCircle(color, lineWidth, progress) {
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
ctx.strokeStyle = '#eeeeee'; // 灰色背景圆环
ctx.lineWidth = lineWidth;
ctx.stroke();
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI * progress);
ctx.strokeStyle = color; // 进度圆环颜色
ctx.lineWidth = lineWidth;
ctx.stroke();
}
function drawText(text) {
ctx.font = '30px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = '#333333'; // 文本颜色
ctx.fillText(text, centerX, centerY);
}
function updateProgress(newProgress) {
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布
progress = newProgress;
drawCircle('#4CAF50', lineWidth, progress); // 使用新进度绘制圆环
drawText(Math.round(progress * 100) + '%'); // 显示新进度百分比
}
// 初始绘制
drawCircle('#4CAF50', lineWidth, progress); // 绿色进度圆环
drawText(Math.round(progress * 100) + '%'); // 显示进度百分比
// 示例:更新进度为50%
// updateProgress(0.5);
在这个示例中,我们首先定义了画布的基本参数,如中心点和半径。drawCircle函数负责绘制灰色背景圆环和绿色进度圆环。drawText函数在圆环中心显示进度百分比。updateProgress函数用于更新进度并重新绘制圆环和文本。你可以通过调用updateProgress函数并传入一个新的进度值(范围从0到1)来更新进度条。
浙公网安备 33010602011771号