Canvas How to - Draw two semicircle arcs on a canvas








Question

We would like to know how to draw two semicircle arcs on a canvas.

Answer


<!DOCTYPE HTML> <html> 
<head>
 <script>
window.onload = function()<!--   w w  w  . j  a va2s  .  co m-->
{ 
   canvas  = document.getElementById("canvasArea"); 
   context = canvas.getContext("2d");

   // A2. ARCS.
   //      x    y   rad sAng eAng antiC  line    fill
   //      ---- --- --- ---- ---- -----  ------  -------
   drawArc(60,  15, 40, 0,   180, false, "aqua", "yellow");
   drawArc(150, 70, 60, 0,   100, true,  "green","white");
   drawArc(250, 15, 50, 350, 170, false, "red",  "pink" );
   drawArc(360, 60, 50, 350, 20,  true,  "blue", "purple");
   
   // B. DRAW arc function.
   function drawArc(xPos, yPos, 
                    radius, 
                    startAngle, endAngle,
                    anticlockwise, 
                    lineColor, fillColor)
   {
      // B1. ANGLES in radians.
      var startAngle = startAngle * (Math.PI/180);
      var endAngle   = endAngle   * (Math.PI/180);

      // B2. RADIUS.
      var radius = radius;

      // B3. ATTRIBUTES.
      context.strokeStyle = lineColor;
      context.fillStyle   = fillColor;
      context.lineWidth   = 8;

      // B4. SHAPE.
      context.beginPath();
      context.arc(xPos, yPos, 
                  radius, 
                  startAngle, endAngle, 
                  anticlockwise);
      context.fill();
      context.stroke();  
   }     
}
</script> 
</head> 
<body> 
<div    style = "width:440px;   height:140px; 
                 margin:0 auto; padding:5px;">
<canvas id    = "canvasArea" 
        width = "440"  height = "140" 
        style = "border:2px solid black">
Your browser doesn't currently support HTML5 Canvas.
</canvas> 
</div> 
</body> 
</html>

The code above is rendered as follows: