Canvas How to - Draw random circles








Question

We would like to know how to draw random circles.

Answer


<!-- www  . j  a v a  2s.co  m-->
<!DOCTYPE HTML> <html> <head> <script>
window.onload = function()
{             
   canvas  = document.getElementById("canvasArea"); 
   context = canvas.getContext("2d");
  
   var numCircles = 9900;
   var maxRadius  = 20;
   var minRadius  = 3;
   var colors     = ["aqua",  "black", "blue",  "fuchsia",
                     "green", "cyan",  "lime",  "maroon",
                     "navy",  "olive", "purple","red",
                     "silver","teal",  "yellow","azure",
                     "gold",  "bisque","pink",  "orange"];
   var numColors  =  colors.length;

   // A3. CREATE circles.
   for(var n=0; n<numCircles; n++)
   {
      // A4. RANDOM values for circle characteristics.
      var xPos       =  Math.random()*canvas.width;
      var yPos       =  Math.random()*canvas.height;
      var radius     =  minRadius+(Math.random()*(maxRadius-minRadius));
      var colorIndex =  Math.random()*(numColors-1);
      colorIndex     =  Math.round(colorIndex);
      var color      =  colors[colorIndex];

      // A5. DRAW circle.
      drawCircle(context, xPos, yPos, radius, color);
   }
};
function drawCircle(context, xPos, yPos, radius, color)
{
   //B1. PARAMETERS for shadow and angles.
   var startAngle        = (Math.PI/180)*0;
   var endAngle          = (Math.PI/180)*360;
   context.shadowColor   = "gray";
   context.shadowOffsetX = 1;
   context.shadowOffsetY = 1;
   context.shadowBlur    = 5;

   //B2. DRAW CIRCLE
   context.beginPath();
   context.arc(xPos, yPos, radius, 
               startAngle, endAngle, false);
   context.fillStyle = color;
   context.fill();              
}
</script> </head> <body> 
<div    style = "width:500px;   height:150px; 
                 margin:0 auto; padding:5px;">
<canvas id    = "canvasArea" 
        width = "500"  height = "550" 
        style = "border:2px solid black">
</canvas> </div> 
</body> </html>

The code above is rendered as follows: