如何使用HTML,Javascript或CamanJS将图像分割成碎片并重新洗牌?

Joh*_*ews 3 javascript image-processing html5-canvas camanjs

我想用原始图像创建拼图图像,这意味着将图像切割成9个(3x3)然后随机洗牌并存储为新图像.有谁知道哪种方法是最好的,以及如何实现它?或许与CamanJS?有没有人有示例代码?

mar*_*rkE 13

在此输入图像描述在此输入图像描述

Canvas可以使用剪辑版本来完成此操作context.drawImage.

context.drawImage 允许您从原始图像剪辑9个子片段,然后在画布上的任何位置绘制它们.

drawImage的剪切版本采用以下参数:

  • 要剪裁的图像:img

  • 剪辑开始的原始图像中的[clipLeft,clipTop]

  • 要从原始图像剪裁的子图像的[clipWidth,clipHeight]大小

  • 画布上的[drawLeft,drawTop]剪切的子图像将开始绘制

  • [drawWidth,drawHeight]被缩放的子图像的大小在画布上要绘制

    • 如果drawWidth==clipWidthdrawHeight==clipHeight,则子图像将以与原始图像相同的大小绘制.

    • 如果drawWidth!==clipWidthdrawHeight!==clipHeight,子图像将被缩放然后绘制.

这是示例代码和一个随机将剪裁的片段绘制到画布上的Demo.它会对一个数组进行混洗以定义各个部分的随机位置,然后使用它来绘制这些部分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;
};
Run Code Online (Sandbox Code Playgroud)
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
Run Code Online (Sandbox Code Playgroud)
<canvas id="canvas" width=300 height=300></canvas>
Run Code Online (Sandbox Code Playgroud)