Canvas 动态绘制圆有锯齿

阅读 11.4k
2 个回答

调用stroke方法描边并将strokeStyle颜色和fillstyle设置成相同的就不会出现缝隙
缝隙的出现可能时因为像素,颜色过渡,斜线总是带锯齿的有关~

    function draw(){
        var end = easeOut(t, sAngle, eAngle, 100) / 100;

        console.log(end);

        ctx.beginPath();
        ctx.moveTo(width / 2, height / 2);//A
        ctx.arc(width / 2, height / 2, width / 2, sAngle, end);//B

        ctx.fillStyle = '#00af0b';//C
        ctx.strokeStyle = "#00af0b";//D
        ctx.fill();
        ctx.stroke();
        sAngle = end;

        if (t < 100) {
            t++;
            requestAnimationFrame(draw2);
        }
    }

运行下面的代码我们能发现,垂直位置的那条缝隙是看不到的,其它的非垂直的斜线的地方都是有的

   function draw1(){
        ctx.save();
        ctx.translate(width / 2, height / 2);
        ctx.rotate(t*10 * Math.PI / 180);
        ctx.beginPath();
        ctx.moveTo(0,0);
        ctx.arc(0, 0, width / 2, 0, 10* Math.PI / 180);
        ctx.fillStyle = '#00af0b';
        ctx.fill();
        ctx.restore();

        console.log(t);

    }


    (function doDraw(){
        draw1();
        t++;
        if(t<10){
            requestAnimationFrame(doDraw);
        }

    }());

简单来说,canvas画图先用类似钢笔的工具描路径,然后填充线(stoke)和其中闭合的内部(fill),而路径是有点儿宽度的,fill 只填充内部,不会填充线,因此,你的代码里加两句就好了:

  ctx.strokeStyle="#00af0b";ctx.stroke();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题