2013-05-21 60 views
0

我有以下的HTML文件:包含arcTo()不拉弧

<!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

任何想法?

+0

試着畫一個圓弧本身:'ctx.arc(250,200,50,Math.PI,Math.PI * 2,true);' –

+0

我特別需要了解這種方法。 – BanksySan

+0

經過一番研究,我發現'arcTo'只在Firefox和Safari中實現。您應該在瀏覽器的控制檯中看到一個錯誤。 –

回答

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')

+0

我是在jQuery的心態,雖然'$('#rectangleCanvas')[0]'有什麼問題? – BanksySan

+1

[這是不必要的低效率](http://vanilla-js.com/) –

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(); 

...至於該功能將定義兩者之間的弧形切線不是從點到點。

順便說一句,在所有支持canvas元素的主流瀏覽器中都支持arcTo函數。