CSS - how to create circle pie canvas like this?

前端 未结 5 967
醉酒成梦
醉酒成梦 2021-01-05 20:03

I really like this element,

\"this

but how to create it? I am not sure what\'s the correct de

5条回答
  •  灰色年华
    2021-01-05 20:06

    FIDDLE with ANIMATION

    Here's my approach:

    var ctx = canvas.getContext('2d');
    
    
    /*
     * in canvas, 0 degrees angle is on the right edge of a circle,
     * while we want to start at the top edge of the circle.
     * We'll use this variable to compensate the difference.
     */
    var relativeAngle = 270;
    
    function drawCanvas() {
    
        ctx.clearRect(0, 0, 90, 90);
        //light blue circle
        ctx.lineWidth = 20;
        ctx.strokeStyle = '#D8E8F7';
        ctx.beginPath();
        ctx.arc(45, 45, 35, 0, 2*Math.PI);
        ctx.stroke();
    
        //dark blue circle
        ctx.strokeStyle = '#66ADF4';
        ctx.beginPath();
        //notice the angle conversion from degrees to radians in the 5th argument
        ctx.arc(45, 45, 35, 1.5*Math.PI, ((angle + relativeAngle) / 180) * Math.PI);
        ctx.stroke();
    
        //text
        ctx.textBaseline = 'middle';
        ctx.textAlign = 'center';
        ctx.fillStyle = '#666';
        ctx.font = 'bold 14px serif';
        // angle conversion to percentage value
        ctx.fillText(parseInt(100 * angle / 360).toString() + '%', 45, 45);
    }
    
    var angle;
    function timeout() {
        angle = parseInt(360 * percent / 100);
        drawCanvas();
    
        if (angle > 360) {
            document.getElementById('run').disabled = false;
            percent = 0;
            return;
        }
    
        percent++;
        setTimeout(timeout, 10);
    };
    
    var percent = 0;
    
    /* START the ANIMATION */
    timeout();
    

    At the bottom of the code you'll find a self evaluating function timeout which calls the drawCanvas function every 10 miliseconds and increments the blue circle angle. I hope everything is clear here. If not, feel free to ask!

    Enjoy it!

提交回复
热议问题