Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cutting an Image into pieces through Javascript

Tags:

I am creating a simple Jigsaw puzzle. In order to do this, I need to cut the picture I am using into 20 pieces. Is there a way in Javascript to cut a picture into 20 equal pieces and save them as 20 different objects within the webpage? Or do I just have to go into photoshop and cut each picture out myself and call it in?

like image 577
TheChes44 Avatar asked Jan 18 '12 15:01

TheChes44


People also ask

How do you split an image into block in HTML?

1 Answer. Show activity on this post. As I told in the comment, You can use <map> tag to divide the image area into two parts. After that you can use jquery for hover functionality and display the content as you like it.

What is image () in JavaScript?

Image() The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document. createElement('img') .


1 Answers

This is easy to do with Canvas. The general idea is:

var image = new Image(); image.onload = cutImageUp; image.src = 'myimage.png';  function cutImageUp() {     var imagePieces = [];     for(var x = 0; x < numColsToCut; ++x) {         for(var y = 0; y < numRowsToCut; ++y) {             var canvas = document.createElement('canvas');             canvas.width = widthOfOnePiece;             canvas.height = heightOfOnePiece;             var context = canvas.getContext('2d');             context.drawImage(image, x * widthOfOnePiece, y * heightOfOnePiece, widthOfOnePiece, heightOfOnePiece, 0, 0, canvas.width, canvas.height);             imagePieces.push(canvas.toDataURL());         }     }      // imagePieces now contains data urls of all the pieces of the image      // load one piece onto the page     var anImageElement = document.getElementById('myImageElementInTheDom');     anImageElement.src = imagePieces[0]; } 
like image 62
Matt Greer Avatar answered Sep 24 '22 14:09

Matt Greer