使用HTML5 Canvas API绘制弧线的教程

2020-04-24 18:56:14易采站长站整理

    window.onload = function(){   
        var canvas = document.getElementById("canvas");   
        canvas.width = 800;   
        canvas.height = 600;   
        var context = canvas.getContext("2d");   
        context.fillStyle = "#FFF";   
        context.fillRect(0,0,800,600);   
  
        drawArcTo(context, 200, 200, 600, 200, 600, 400, 100);   
    };   
  
    function drawArcTo(cxt, x0, y0, x1, y1, x2, y2, r){   
        cxt.beginPath();   
        cxt.moveTo(x0, y0);   
        cxt.arcTo(x1, y1, x2, y2, r);   
  
        cxt.lineWidth = 6;   
        cxt.strokeStyle = "red";   
        cxt.stroke();   
  
        cxt.beginPath();   
        cxt.moveTo(x0, y0);   
        cxt.lineTo(x1, y1);   
        cxt.lineTo(x2, y2);   
  
        cxt.lineWidth = 1;   
        cxt.strokeStyle = "#0088AA";   
        cxt.stroke();   
  
    }   
</script>   
</body>   
</html>  

运行结果:
2016322110438098.jpg (850×500)

这个案例也很好说明了arcTo()的各个关键点的作用。为了更清楚的解释,我再标注一个分析图。
2016322110502905.jpg (600×425)

这里注意一下,arcTo()绘制的起点是(x0, y0),但(x0, y0)不一定是圆弧的切点。真正的arcTo()函数只传入(x1, y1)和(x2, y2)。其中(x1, y1)称为控制点,(x2, y2)是圆弧终点的切点,它不一定在圆弧上。但(x0, y0)一定在圆弧上。