Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 6th, 2012  |  syntax: None  |  size: 1.15 KB  |  hits: 19  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Cutting an Image into pieces through Javascript
  2. <div class="puzzle piece1"></div>
  3. <div class="puzzle piece2"></div>
  4.        
  5. .puzzle {
  6.    background-image:url(/images/puzzle.jpg);
  7.    width:100px;
  8.    height:100px;
  9. }
  10.  
  11. .piece1 {
  12.    background-position:0 0
  13. }
  14.  
  15. .piece2 {
  16.    background-position:-100px -100px
  17. }
  18.        
  19. var image = new Image();
  20. image.onload = cutImageUp;
  21. image.src = 'myimage.png';
  22.  
  23. function cutImageUp() {
  24.     var imagePieces = [];
  25.     for(var x = 0; x < numColsToCut; ++x) {
  26.         for(var y = 0; y < numRowsToCut; ++y) {
  27.             var canvas = document.createElement('canvas');
  28.             canvas.width = widthOfOnePiece;
  29.             canvas.height = heightOfOnePiece;
  30.             var context = canvas.getContext('2d');
  31.             context.drawImage(image, x * widthOfOnePiece, y * heightOfOnePiece, widthOfOnePiece, heightOfOnePiece, 0, 0, canvas.width, canvas.height);
  32.             imagePieces.push(canvas.toDataUrl());
  33.         }
  34.     }
  35.  
  36.     // imagePieces now contains data urls of all the pieces of the image
  37.  
  38.     // load one piece onto the page
  39.     var anImageElement = document.getElementById('myImageElementInTheDom');
  40.     anImageElement.src = imagePieces[0];
  41. }