【问题标题】:How to split up an image in pieces and reshuffle it, using HTML, Javascript or CamanJS?如何使用 HTML、Javascript 或 CamanJS 将图像分成几部分并重新洗牌?
【发布时间】:2015-01-19 19:51:21
【问题描述】:

我想从原始图像中创建拼图图像,这意味着将图像切成 9 块 (3x3),然后将图像打乱并存储为新图像。有谁知道哪种方法最好这样做以及如何实现?也许与 CamanJS?谁有示例代码?

【问题讨论】:

    标签: javascript image-processing html5-canvas camanjs


    【解决方案1】:

    Canvas 可以使用 context.drawImage 的剪辑版本来做到这一点。

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

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

    • 要裁剪的图像img

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

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

    • Canvas 上的 [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;
    };
    body{ background-color: ivory; padding:10px; }
    #canvas{border:1px solid red;}
    &lt;canvas id="canvas" width=300 height=300&gt;&lt;/canvas&gt;

    【讨论】:

    • 这是一个病态的反应。从来没有得到如此详尽的答案。如果可能的话,我现在就把我所有的分数都给你。非常感谢!!!!
    • 快速问题,是否可以将画布分成几部分,而不是 img?谢谢。
    猜你喜欢
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 2014-04-08
    相关资源
    最近更新 更多