ArcTo()没有绘制弧

时间:2013-05-21 00:44:39

标签: javascript html5 canvas html5-canvas

我有以下HTML文件:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Canvas Hello World</title>
    <link href="default.css" rel="stylesheet" />
    <script src="jquery-2.0.0.min.js"></script>
</head>
<body>
    <h1>ArcTo</h1>
    <h2>Two arcs</h2>
    <canvas id="arcToNormalCanvas" width="500" height="500">HTML5 not supported
    </canvas>
    <hr />

    <h1>Simple drawing:</h1>
    <canvas id="rectangleCanvas" width="500" height="500">HTML5 not supported
    </canvas>
    <hr />

    <script>
        $(document).ready(function () {
            doRectangleCanvas();
            drawTwoArcs();
        });

        function doRectangleCanvas() {
            var canvas = $('#rectangleCanvas')[0],
                ctx = canvas.getContext('2d');

            ctx.fillRect(50, 100, 150, 200);
            ctx.stroke();
        }

        function drawTwoArcs() {
            var canvas = $('#arcToNormalCanvas')[0],
                ctx = canvas.getContext('2d');
            ctx.strokeStyle = 'blue';
            ctx.lineWidth = 5;
            ctx.beginPath();
            ctx.moveTo(100, 100);
            ctx.lineTo(200, 200);
            ctx.moveTo(300, 200);
            ctx.lineTo(400, 100);
            ctx.stroke();

            ctx.beginPath();
            ctx.strokeStyle = 'green';
            ctx.moveTo(200, 200);
            ctx.arcTo(200, 200, 300, 200, 100);
            ctx.stroke();
        }
    </script>
</body>
</html>

但是,输出只是线条,没有弧!

Canvas of html file above

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

arcTo仅受Firefox和Safari支持。要获得完整的浏览器支持,您应该使用arc

ctx.beginPath();
ctx.arc(250,200,50,Math.PI,Math.PI*2,true);
ctx.strokeStyle = "green";
ctx.stroke();

另外,我不得不问,为什么在使用$('#rectangleCanvas')[0]时使用document.getElementById('rectangleCanvas')

答案 1 :(得分:0)

如果你想连接两条线,这就是我想你想要的,我必须改变这一行......

//...
ctx.moveTo(200, 200);
ctx.arcTo(250, 250, 300, 200, 50);
// A radius of 100 is not what you want I believe.
// I used 50 for this example.
// You might want Math.cos(Math.Pi / 4) * 100, which is around 70.7

// You might also want to add here a line to actually connect with (300, 200). As if you use a too short or too long radius your arc will not be connected.
ctx.lineTo(300, 200);
ctx.stroke();

...由于此函数将在两个切线之间定义一个不是从点到点的弧。

BTW,arcTo函数在支持canvas元素的所有主流浏览器中得到很好的支持。