HTML5 Game - Canvas Image Pixelation

Introduction

Pixelation can make an image unrecognizable without removing an entire section.

We can split an image into a grid and average the colors within each segment, or pick a color within each segment.

Demo

ResultView the demo in separate window

<!DOCTYPE html>

<html>
  <head>
    <title>Manipulating images and video</title>
    <meta charset="utf-8">
    /*from   w w  w . j  a  v  a  2  s  .c  o  m*/
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    
    <script type="text/javascript">
      $(document).ready(function() {  
        let canvas = $("#myCanvas");
        let context = canvas.get(0).getContext("2d");
        
        // Pixelating
        let image = new Image();
        image.src = "http://java2s.com/style/download.png";
        $(image).load(function() {
          context.drawImage(image, 0, 0, 1024, 683, 0, 0, 500, 500);
          
          let imageData = context.getImageData(0, 0, canvas.width(), canvas.height());
          let pixels = imageData.data;
          
          // Clear the image
          context.clearRect(0, 0, canvas.width(), canvas.height());
          
          // Number of tiles
          let numTileRows = 20;
          let numTileCols = 20;
          
          // Dimensions of each tile
          let tileWidth = imageData.width/numTileCols;
          let tileHeight = imageData.height/numTileRows;
          
          // Loop through each tile
          for (let r = 0; r < numTileRows; r++) {
            for (let c = 0; c < numTileCols; c++) {
              let x = (c*tileWidth)+(tileWidth/2);
              let y = (r*tileHeight)+(tileHeight/2);
              
              // Use Math.floor to convert the pixel positions to integers
              let pos = (Math.floor(y)*(imageData.width*4))+(Math.floor(x)*4);
              
              let red = pixels[pos];
              let green = pixels[pos+1];
              let blue = pixels[pos+2];
              
              context.fillStyle = "rgb("+red+", "+green+", "+blue+")";
              
              // Draw the pixelated rectangle
              context.fillRect(x-(tileWidth/2), y-(tileHeight/2), tileWidth, tileHeight);
              
            };
          };
        });
      
      });
    </script>
  </head>
  
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

Related Topics