<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Ring with Rounded Ends</title>
<style>
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const radius = 80; // 圆环半径
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const startAngle = -Math.PI / 2; // 12点钟方向
let endAngle = startAngle + (Math.PI * 2 * 0.25); // 初始长度为 270度
const lineWidth = 10; // 圆环宽度
const roundedRadius = lineWidth / 2; // 圆角半径(等于线宽的一半)
// 绘制圆环
function drawRing() {
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制圆弧
ctx.beginPath();
ctx.arc(centerX, centerY, radius, startAngle, endAngle, true); // 逆时针绘制
ctx.lineWidth = lineWidth;
ctx.strokeStyle = '#3498db';
ctx.stroke();
// 绘制起点圆角
const startX = centerX + Math.cos(startAngle) * radius;
const startY = centerY + Math.sin(startAngle) * radius;
ctx.beginPath();
ctx.arc(startX, startY, roundedRadius, 0, Math.PI * 2);
ctx.fillStyle = '#3498db';
ctx.fill();
// 绘制终点圆角
const endX = centerX + Math.cos(endAngle) * radius;
const endY = centerY + Math.sin(endAngle) * radius;
ctx.beginPath();
ctx.arc(endX, endY, roundedRadius, 0, Math.PI * 2);
ctx.fillStyle = '#3498db';
ctx.fill();
}
// 初始化绘制
drawRing();
// 动态控制圆环长度
function updateRing(progress) {
endAngle = startAngle + (Math.PI * 2 * progress);
drawRing();
}
// 示例:更新圆环长度为 50%
updateRing(0.5);
</script>
</body>
</html>
02-24
1508

11-04
181
