canvas画圆又毛边

canvas使用arc()画园有毛边,如图:,只需给其添加width,height即可,直接上代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>圆形</title>
</head>
<body>
    <canvas class="can-circle" id="circle"></canvas>

    <script type="text/javascript">
        function _circle(canvas,angle){
            var ang1 = 270+angle;
            var ang = ang1/180 * Math.PI;
            var ctx = canvas.getContext("2d");
            //解决毛边
            canvas.width = 120;
            canvas.height = 120;
            //灰色
            ctx.beginPath();
            ctx.lineWidth = 10;
            ctx.strokeStyle = '#ccc'; 
            ctx.arc(60,60,50,0,Math.PI*2);
            ctx.stroke();

            ctx.beginPath();
            ctx.lineWidth = 10;
            ctx.strokeStyle = '#6C0'; 
            ctx.arc(60,60,50,Math.PI*1.5,ang);
            ctx.stroke();
        }
        function fun(id,a){
            var b = 0;
            a = Math.round(a*360);
            var set = setInterval(function(){
                _circle(id,b);
                b++;
                if(b === (a+1)){
                    clearInterval(set);
                }
            },0);
        }
        fun(document.getElementById("circle"),0.8);
        document.getElementById("circle").onmouseenter = function(){
            fun(document.getElementById("circle"),0.8);
        }
    </script>
</body>
</html>

运行后:,这样是不是美观了很多?

看上面代码可知,解决毛边的主要两句代码是:

canvas.width = 120;
canvas.height = 120;

此widthheight可以任意设置,只是为了美观,不遮盖其他文件即本身现实才都设置为了120px。注意,此处widthheight的单位不用添加,默认是px。

原文地址:https://www.cnblogs.com/cyj7/p/4978472.html