uPaymeiFixit
uPaymeiFixit

Reputation: 343

How would I mimic CanvasRenderingContext2D's arc method? - Javascript

I have been trying to mimic the arc method that belongs to the CanvasRenderingContext2D class for HTML5's canvas element. I have it somewhat working, but I just can't seem to wrap my head around the whole thing.

I made a jsfiddle test environment to make testing the function go faster, so feel free to use it.

I am trying to make this for a few of my projects that I want to port to the IvanK library, which does not appear to support circle strokes.

Upvotes: 0

Views: 223

Answers (2)

uPaymeiFixit
uPaymeiFixit

Reputation: 343

So I just spent way too much time trying to figure this out, and I think I finally got it. This is the function I finally came up with.

arcL = function( x, y, radius, startAngle, endAngle, anticlockwise )
{
    if ( anticlockwise )
    {
        var t = startAngle
        startAngle = endAngle
        endAngle = t
    }

    var d = Math.abs(endAngle - startAngle);
    if ( d >= Math.PI * 2 )
        endAngle = startAngle + Math.PI * 2;
    else
    {
        if ( endAngle < startAngle )
            endAngle += tau
        else
            endAngle = startAngle + d;
    }

    ctx.moveTo( x + radius * Math.cos( startAngle ), y + radius * Math.sin( startAngle) );
    for ( ; startAngle < endAngle; startAngle += 0.02 )
        ctx.lineTo( x + radius * Math.cos( startAngle ), y + radius * Math.sin( startAngle ) );
}

jsfiddle

Upvotes: 0

Jani Hartikainen
Jani Hartikainen

Reputation: 43243

You can use the midpoint circle algorithm to draw a circle or a circle segment pixel by pixel

Upvotes: 1

Related Questions