How can I split an image into chunks and drag and drop using HTML, Javascript or CamanJS?

I want to create a puzzle image from the original images, which means the image is cut into 9 pieces (3x3) and then shuffled and saved as a new image. Does anyone know which method is best for this and how to achieve it? Perhaps with CamanJS? Does anyone have some sample code?

+3


source to share


1 answer


enter image description hereenter image description here

Canvas can do this using the clipping version context.drawImage

.

context.drawImage

allows you to crop your 9 slices from your original image and then paint them anywhere on the canvas.

The cropped version of drawImage takes the following arguments:



  • image :img

  • [clipLeft, clipTop] in the original image where clipping starts

  • the size [clipWidth, clipHeight] of the sub-image to be cropped from the original image

  • [drawLeft, drawTop] on the canvas where the cropped sub-image will start to draw

  • [drawWidth, drawHeight] is the scaled size of the sub-image to be drawn onto the canvas

    • If drawWidth==clipWidth

      and drawHeight==clipHeight

      , the sub-image will be drawn with the same size cut from the original.

    • If drawWidth!==clipWidth

      and drawHeight!==clipHeight

      , the sub-image will be scaled and then drawn.

Here is some sample code and demo that randomly draws cropped slices to the canvas. It shuffles the array to determine random positions for the shapes, and then draws those shapes with drawImage

.

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var rows=3;
var cols=3;

var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/sailboat.png";
function start(){

  var iw=canvas.width=img.width;
  var ih=canvas.height=img.height;
  var pieceWidth=iw/cols;
  var pieceHeight=ih/rows;

  var pieces = [
    {col:0,row:0},
    {col:1,row:0},
    {col:2,row:0},
    {col:0,row:1},
    {col:1,row:1},
    {col:2,row:1},
    {col:0,row:2},
    {col:1,row:2},
    {col:2,row:2},
  ]
    shuffle(pieces);

    var i=0;
    for(var y=0;y<rows;y++){
    for(var x=0;x<cols;x++){
    var p=pieces[i++];
  ctx.drawImage(
    // from the original image
    img,
    // take the next x,y piece
    x*pieceWidth, y*pieceHeight, pieceWidth, pieceHeight,
    // draw it on canvas based on the shuffled pieces[] array
    p.col*pieceWidth, p.row*pieceHeight, pieceWidth, pieceHeight
  );
}}


}

function shuffle(a){
  for(var j, x, i = a.length; i; j = Math.floor(Math.random() * i), x = a[--i], a[i] = a[j], a[j] = x);
  return a;
};
      

body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
      

<canvas id="canvas" width=300 height=300></canvas>
      

Run codeHide result


+12


source







All Articles