Matthias Friedrich Matthias Friedrich - 4 months ago 27
Javascript Question

canvas rotation calculation: how to calculate the new position?

I try to draw a rotated line and after rotating to draw a point on the start and end of the line.

This is my code (doesn't work correctly)

<!-- 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 Demo : http://jsfiddle.net/UT29j/

Has someone an idea?

Answer

Rotation and translation apply to everything drawn. You do not need to manipulate the coordinates yourself.

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