Drawing circles and arcs

The ctx.arc(cx, cy, radius, startAngle, endAngle, drawInverse) method is useful for drawing arcs of circles. It takes the center of the circle/arc, its radius, the starting angle of the arc (turning clockwise), the ending angle of the arc, and an optional parameter we will talk about later.

TYPICAL USAGE

Typical usage for drawing an arc/circle/ellipse is:

  1. ctx.arc(centerX, centerY, radius, startAngle, endAngle); // clockwise drawing
  2. ctx.arc(centerX, centerY, radius, startAngle, endAngle, false);

EXAMPLE 1: DRAWING AN ARC WITH RADIUS = 50, STARTING ANGLE = 0, END ANGLE = PI/2

Try this example online: http://jsbin.com/tikite/1/edit

  1. ctx.beginPath();
  2. // we ommited the last parameter
  3. ctx.arc(10075500Math.PI/2);
  4.  
  5. ctx.lineWidth 10;
  6. ctx.stroke();

If we change the last parameter (we omitted it, so it took a value of false by default):

  1. ctx.beginPath();
  2. // we omitted the last parameter
  3. ctx.arc(10075500Math.PI/2, true);
  4.  
  5. ctx.lineWidth 10;
  6. ctx.stroke();

EXAMPLE 2: DRAWING A FULL CIRCLE (FILLED + OUTLINED)

Try this example: http://jsbin.com/gazuba/2/edit

  1. var canvas = document.getElementById(“myCanvas”);
  2. var ctx = canvas.getContext(“2d”);
  3. var centerX = canvas.width / 2;
  4. var centerY = canvas.height / 2;
  5. var radius = 70;
  6. ctx.beginPath();
  7. // Add to the path a full circle (from 0 to 2PI)
  8. ctx.arc(centerX, centerY, radius, 0, 2*Math.PI, false);
  9. // With path drawing you can change the context
  10. // properties until a call to stroke() or fill() is performed
  11. ctx.fillStyle = “lightBlue”;
  12. // Draws the filled circle in light blue
  13. ctx.fill();
  14. // Prepare for the outline
  15. ctx.lineWidth = 5;
  16. ctx.strokeStyle = “black”;
  17. // draws the path (the circle) AGAIN, this
  18. // time in wireframe
  19. ctx.stroke();
  20. // Notice we called ctx.arc() only once ! And drew it twice
  21. // with different styles

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s