canvas实现的圆环

<!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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值