Draw a circle filled with random color squares on HTML5 canvas

When we need to fill a circle with 1x1 pixels, all with different colors in a browser, we can use HTML5 Canvas with a layered approach.

Approach

  • Drawing all pixels with random colors in a 200x200 grid on a canvas
  • Changing composite mode to clip content
  • Drawing circle on top to mask the random pixels

Example

Here's how to create a circle filled with colorful random squares:

<!DOCTYPE html>
<html>
<head>
  <title>Random Color Circle</title>
</head>
<body>
  <canvas id="canvas" width="200" height="200" style="border: 1px solid #000;"></canvas>
  
  <script>
    var canvas1 = document.getElementById('canvas'), // getting canvas element
        ctx1 = canvas1.getContext('2d'), // getting context
        x, y = 0, // initializing x and y coordinates
        diamet = canvas1.width,
        radius = diamet * 0.4;
    
    ctx1.translate(0.5, 0.5); // Making pixels sharper
    
    // Draw random colored squares in a grid
    for(; y < diamet; y++) { // y grid
      for(x = 0; x < diamet; x++) { // x grid
        ctx1.fillStyle = getRndColor(); // Random color setting
        ctx1.fillRect(x, y, 1, 1); // Drawing a 1x1 pixel
      }
    }
    
    // Create circle mask
    // Removes pixels outside next shape
    ctx1.globalCompositeOperation = 'destination-in';
    ctx1.beginPath();
    ctx1.arc(diamet/2, diamet/2, radius, 0, 2*Math.PI);
    ctx1.fill();
    
    // Reset composite operation
    ctx1.globalCompositeOperation = 'source-over';
    
    function getRndColor() {
      var r = 255*Math.random()|0,
          g = 255*Math.random()|0,
          b = 255*Math.random()|0;
      return 'rgb(' + r + ',' + g + ',' + b + ')';
    }
  </script>
</body>
</html>

How It Works

  1. Grid Generation: The nested loops create a 200x200 grid of 1x1 colored squares
  2. Random Colors: Each pixel gets a random RGB color using Math.random()
  3. Composite Operation: destination-in mode keeps only pixels that overlap with the next shape
  4. Circle Mask: Drawing a circle removes all pixels outside the circular boundary

Key Points

  • translate(0.5, 0.5) creates sharper pixel rendering
  • destination-in composite mode acts as a clipping mask
  • fillRect(x, y, 1, 1) draws individual pixels
  • Always reset globalCompositeOperation to source-over after masking

Conclusion

This technique combines random pixel generation with canvas composite operations to create artistic effects. The destination-in mode provides an elegant way to mask content into circular shapes.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements