code prettify

Thursday, 20 November 2014

How to draw a quarter circle arc using canvas?

Using canvas, we can draw a circle or a circular arc using the arc method of the context object.

The basic syntax of the arc method is:

context.arc(x, y, radius, start_angle, end_angle, direction)

Parameters:
x, y              are the center point co-ordinates
radius          (of the arc)
start_angle  Position where the arc should start (in radians)
end_angle   Position where the arc should end (in radians)
direction     Whether to start tracing in clockwise or anti-clockwise direction.  (bool)
                   true indicates anti-clockwise and false indicates clockwise direction.

So one can modify the start_angle, end_angle and the direction to trace any part of a circle. To draw a quarter circle arc, we need to start at 0 degree and end at 270 degrees but we need to trace in anti-clockwise direction so direction value would be true.

Relationship between radian and degrees:

2 * Pi  Radians = 360 degrees

Code for a quarter-circle arc:

<canvas width="600" height="400"></canvas>
<script>
    var canvas = document.getElementsByTagName("canvas")[0];
    var context = canvas.getContext("2d");

    context.beginPath();
    context.arc(100, 100, 75, 0, degreesToRadians(270), true);
    context.stroke();

    function degreesToRadians(degrees) {
        return (degrees * Math.PI) / 180;
    }
</script>


Click here for a demo.


1 comment:

  1. The above mentioned matter is easy to not only understand but also explain. Even I can elaborate subject of this article now very easily because I it is easy to understand for me. Really a creative expert skill possessed by author.maxim 9

    ReplyDelete