Using css/js to realize the square to represent the percentage

clipboard.png

Border scale display percentage

Jul.06,2021

can I use canvas? I have a plug-in


this is the same as the circular progress bar, except that the border-radius is smaller.

write it casually, and realize the principle

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Rect Percent</title>
    <style type="text/css">
    .cp {position:relative;width:100px;height:100px;border-radius:10px;box-shadow:0 0 2px 0 -sharp000;overflow:hidden;}
    .cp .half-bg {position:absolute;width:50px;height:100px;background-color:-sharpFFC300;box-sizing:border-box;overflow:hidden;}
    .cp .half-bg-l {left:0;}
    .cp .half-bg-r {left:50px;}
    .cp .half-bg .half {width:200%;height:200%;margin-top:-100%;background-color:-sharpCCC;}
    .cp .half-bg .half-l {margin-left:-100%;transform-origin:right center;transform:rotate(0deg);}
    .cp .half-bg .half-r {transform-origin:left center;transform:rotate(60deg);}
    .cp .num {position:absolute;top:10px;left:10px;width:80px;height:80px;font-family:Consolas, monospace;text-align:center;line-height:80px;border-radius:10px;background-color:rgba(255,255,255,0.9);}
    </style>
    <script>
    document.addEventListener('DOMContentLoaded', function(){

        let domCp = document.querySelector('.cp');

        function update()
        {
            let percent = parseInt(domCp.getAttribute('data-percent'), 10);
            if(isNaN(percent) === true || percent > 100)
                percent = 0;

            console.log(percent);
            if(percent < 50)
            {
                domCp.querySelector('.half-r').style.transform = 'rotate('+(percent/50 * 180)+'deg)';
                domCp.querySelector('.half-l').style.transform = 'rotate(0deg)';
            }
            else
            {
                domCp.querySelector('.half-r').style.transform = 'rotate(180deg)';
                domCp.querySelector('.half-l').style.transform = 'rotate('+(((percent-50)/50 * 180))+'deg)';
            }

            domCp.querySelector('.num').innerHTML = percent + '%';

            domCp.setAttribute('data-percent', percent+1);

            setTimeout(update, 100);
        }

        setTimeout(update, 10);
    });
    </script>
</head>
<body>
<div class="cp" data-percent="0">
    <div class="half-bg half-bg-l">
        <div class="half half-l"></div>
    </div>
    <div class="half-bg half-bg-r">
        <div class="half half-r"></div>
    </div>
    <div class="num">60%</div>
</div>
</body>
</html>

Menu