如何使用HTML、Javascript或CamanJS将图像切成碎片并重新拼合?

4

我想将原始图像制作成拼图,也就是将一张图片切成9个部分(3x3),然后打乱并保存为新的图像。请问有哪种方法最适合这样做,如何实现呢?也许可以使用CamanJS?请问有没有示例代码?

1个回答

18

enter image description hereenter image description here

使用context.drawImage的剪切版本,Canvas可以实现此操作。

context.drawImage允许您从原始图像中剪切出9个子碎片,然后将它们绘制到画布上的任何位置。

drawImage的剪切版本需要这些参数:

  • 要剪裁的图像img

  • 在原始图像中[clipLeft,clipTop]开始剪裁

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

  • 裁剪的子图像将开始绘制到[drawLeft,drawTop]处的Canvas上

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

    • 如果drawWidth==clipWidth并且drawHeight==clipHeight,则子图像将以与从原始图像剪切的相同大小绘制。

    • 如果drawWidth!==clipWidth并且drawHeight!==clipHeight,则将缩放子图像然后绘制它们。

这是示例代码和演示,随机将裁剪的碎片绘制到画布上。它会洗牌一个数组,以定义碎片的随机位置,然后使用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>


1
这是一个非常棒的回答。我从来没有得到过像这样详细的答案。如果可能的话,我现在会把所有的分数都给你。非常感谢!!! - WJA
快速问题,是否可以将画布分成几个部分,而不是图像?谢谢。 - AMG

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接