ajbee
ajbee

Reputation: 3641

Create a Circle Based from a line angle and x-positive axis in html canvas

Basically I know the concept on how to create the line but I'm having difficulties on how to make the logic for the angle value and the circle in that kind of interface.

Here is a sample

semicirc = function() 
{
    var canvas = document.getElementById('circle-canvas');

    if (canvas && canvas.getContext) {
        var context = canvas.getContext('2d');
        if (context) {
            context.strokeStyle = "#369";
            context.lineWidth = 4;


            j = canvas.width / 2;
            k = canvas.height / 2;
            r = canvas.width / 4; 

            function computeX(theta, r, j, k){ return r * Math.cos(theta) + j; }
            function computeY(theta, r, j, k){ return r * Math.sin(theta) + k; }

            start = 0;
            context.lineTo(computeX(start, r, j, k), computeY(start, r, j, k));
            for(var theta = start; theta <= (Math.PI); theta += .1) 
            {
                x = computeX(theta, r, j, k);
                y = computeY(theta, r, j, k),

                context.lineTo(x, y);
            }
            context.stroke();
            context.closePath();
        }
    }
}
semicirc();

Note: There are two points which can be moved.(already working)

Here are the sample output:enter image description here

Upvotes: 1

Views: 117

Answers (1)

Lutz Lehmann
Lutz Lehmann

Reputation: 25972

In cartesian coordinates, you get the (visual, mathematically positiv oriented) angle for the segment from center M to point A as

dy = M.y - A.y;
dx = A.x - M.x:
phi = atan2(dy,dx);

The canvas arc uses the Cartesian coordinate system without regard that in screen coordinates it is flipped on the x axis. Thus to get a visual angle of phi, internally one has to use -phi.

counterclock = ( -phi < 0 );
ctx.arc(M.x, M.y, Radius, 0, -phi, counterclock); 

should give the correct arc.

Upvotes: 2

Related Questions