HTML5 Game - Creating a mosaic effect on image

Description

Creating a mosaic effect on image

Demo

ResultView the demo in separate window

<!DOCTYPE html>

<html>
  <head>
    <title>Manipulating images and video</title>
    <meta charset="utf-8">
    /*from  w  ww .  j a  va  2s  . c om*/
    <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");
        
        // Creating a mosaic
        let imageData = context.createImageData(500, 500);
        let pixels = imageData.data;
        
        // Number of mosaic segments
        let numTileRows = 4;
        let numTileCols = 4;
        
        // Dimensions of each segment
        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++) {
            // Set the pixel values for each tile
            let red = Math.floor(Math.random()*255);
            let green = Math.floor(Math.random()*255);
            let blue = Math.floor(Math.random()*255);
        
            // Loop through each tile pixel
            for (let tr = 0; tr < tileHeight; tr++) {
              for (let tc = 0; tc < tileWidth; tc++) {
                // Calculate the true position of the tile pixel
                let trueX = (c*tileWidth)+tc;
                let trueY = (r*tileHeight)+tr;
            
                // Calculate the position of the current pixel in the array
                let pos = (trueY*(imageData.width*4))+(trueX*4);
                
                // Assign the colour to each pixel
                pixels[pos] = red;
                pixels[pos+1] = green;
                pixels[pos+2] = blue;
                pixels[pos+3] = 255;
              };
            };
          };
        };
        
        // Draw image data to the canvas
        context.putImageData(imageData, 0, 0);
      
      });
    </script>
  </head>
  
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

Related Topic