HTML Canvas Save to image

Description

HTML Canvas Save to image

View in separate window

<!DOCTYPE html>

<html>
  <head>
    <title>Manipulating images and video</title>
    <meta charset="utf-8">
    //from   ww w .j  av a2 s .  co  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() {  
        var canvas = $("#myCanvas");
        var context = canvas.get(0).getContext("2d");

        // Pixelating
        var image = new Image();
        image.src = "image1.png";
        $(image).load(function() {
          context.drawImage(image, 0, 0, 1024, 683, 0, 0, 500, 500);
          
          var imageData = context.getImageData(0, 0, canvas.width(), canvas.height());
          var pixels = imageData.data;
          
          // Clear the image
          context.clearRect(0, 0, canvas.width(), canvas.height());
          
          // Number of tiles
          var numTileRows = 20;
          var numTileCols = 20;
          
          // Dimensions of each tile
          var tileWidth = imageData.width/numTileCols;
          var tileHeight = imageData.height/numTileRows;
          
          // Loop through each tile
          for (var r = 0; r < numTileRows; r++) {
            for (var c = 0; c < numTileCols; c++) {
              var x = (c*tileWidth)+(tileWidth/2);
              var y = (r*tileHeight)+(tileHeight/2);
              
              // Use Math.floor to convert the pixel positions to integers
              var pos = (Math.floor(y)*(imageData.width*4))+(Math.floor(x)*4);
              
              var red = pixels[pos+0];
              var green = pixels[pos+1];
              var blue = pixels[pos+2];
              
              context.fillStyle = "rgb("+red+", "+green+", "+blue+")";
              
              // Draw the pixelated circles
              context.beginPath();
              context.arc(x, y, tileWidth/2, 0, Math.PI*2);
              context.closePath();
              context.fill();
            };
          };
          
          // Convert the canvas into an image data URL
          var dataURL = canvas.get(0).toDataURL();
          var img = $("<img></img>");
          img.attr("src", dataURL);
        
          // Replace the canvas with the image of the canvas
          canvas.replaceWith(img);
        });  
      });
    </script>
  </head>
  
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>



PreviousNext

Related