Cutting an Image into pieces through Javascript

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?

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

var image = new Image();
image.onload = cutImageUp;

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 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];

You can do this by setting the image as a background on a div, then setting its background-position. This is basically the same as using CSS Sprites.

(assume pieces are 100 x 100px)

<div class="puzzle piece1"></div>
<div class="puzzle piece2"></div>


.puzzle {

.piece1 {
   background-position:0 0

.piece2 {
   background-position:-100px -100px

you can use the drawImage method to slice parts of a source image and draw them to a canvas:

drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

something like :


 function draw() {
    var ctx = document.getElementById('canvas').getContext('2d');

then create draggable content for your new entities :

<div id="columns">
   <div class="column" draggable="true"><header>A</header></div>
   <div class="column" draggable="true"><header>B</header></div>
   <div class="column" draggable="true"><header>C</header></div>

Read More:   @Url.Content in separate javascript file using ASPNET MVC 3 and Razor

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts