2013-01-02 57 views
0

我嘗試繪製一條旋轉線,並在旋轉後在線的開始和結束處繪製一個點。帆布旋轉計算:如何計算新的位置?

這是我的代碼(不正常)

<!-- language: lang-html --> 
<html><head><title>test</title></head><body> 

    <canvas id="canvas" width="100" height="100"></canvas> 

    <script type="text/javascript"> 

     var _context = document.getElementById("canvas").getContext('2d'); 

     var x = 40; 
     var y = 40; 
     var angle = 0.2; 

     _context.beginPath(); 
     _context.translate(x, y); 

     //rotate and draw line 
     _context.rotate(angle); 
     _context.moveTo(0, 0); 
     _context.lineTo(0, 40); 
     _context.stroke(); 

     //calculate the new x,y position from line 
     x = x * Math.cos(angle) - y * Math.sin(angle); 
     y = x * Math.sin(angle) + y * Math.cos(angle); 

     //draw a point to this coords 
     _context.save(); 
     _context.fillStyle = "orange"; 
     _context.beginPath(); 
     _context.arc(x, y, 4, 0, 2*Math.PI, true); 
     _context.fill(); 

    </script> 
</body></html> 

的jsfiddle演示:http://jsfiddle.net/UT29j/

有別人的想法?

回答

1

旋轉和平移適用於繪製的所有內容。你不需要自己操縱座標。

<html><head><title>test</title></head><body> 

    <canvas id="canvas" width="100" height="100"></canvas> 

    <script type="text/javascript"> 

     var _context = document.getElementById("canvas").getContext('2d'); 

     var angle = 0.2; 

     // rotate and translate 
     _context.translate(40, 40); 
     _context.rotate(angle); 

     // draw line 
     _context.beginPath(); 
     _context.moveTo(0, 0); 
     _context.lineTo(0, 40); 
     _context.stroke(); 

     //draw a point to this coords 
     _context.save(); 
     _context.fillStyle = "orange"; 
     _context.beginPath(); 
     _context.arc(0, 40, 4, 0, 2*Math.PI, true); 
     _context.arc(0, 0, 4, 0, 2*Math.PI, true); 
     _context.fill(); 
    </script> 
</body></html> 
+0

非常感謝:)帆布神;) –

+0

其實,我從來沒有在任何項目中使用帆布。 :) –