画布旋转计算:如何计算新位置?

时间:2013-01-02 19:51:51

标签: javascript canvas rotation position

我尝试绘制一条旋转的线,并在旋转后在线的起点和终点画一个点。

这是我的代码(无法正常工作)

<!-- 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 个答案:

答案 0 :(得分: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>