Canvas How to - Draw circles with different color








Question

We would like to know how to draw circles with different color.

Answer


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

   // A2. CIRCLES.
   //         x    y   rad line     fill
   //         ---- --- --- ------   -------
   drawCircle(60,  15, 40, "aqua",  "yellow");
   drawCircle(150, 70, 60, "green", "white" );
   drawCircle(250, 15, 50, "red",   "pink"  );
   drawCircle(360, 60, 50, "blue",  "purple");
   
   // B. DRAW circle function.
   function drawCircle(xPos, yPos, radius, lineColor, fillColor)
   {
      // B1. ANGLES in radians.
      var startAngle =   0 * (Math.PI/180);
      var endAngle   = 360 * (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, false);
      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">
</canvas> 
</div> 
</body> 
</html>

The code above is rendered as follows: