通过Javascript将图像切割成碎片

时间:2012-01-18 15:39:02

标签: javascript html html5

我正在创建一个简单的拼图游戏。为了做到这一点,我需要将我使用的图片切成20块。有没有办法在Javascript中将图片分割成20个相等的部分,并将它们保存为网页中的20个不同的对象?或者我是否只需要进入Photoshop并自己剪切每张照片并将其调用?

3 个答案:

答案 0 :(得分:19)

您可以通过将图像设置为div上的背景,然后设置其背景位置来完成此操作。这与使用CSS Sprites基本相同。

(假设件数为100 x 100px)

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

CSS:

.puzzle {
   background-image:url(/images/puzzle.jpg);
   width:100px;
   height:100px;
}

.piece1 {
   background-position:0 0
}

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

答案 1 :(得分:18)

使用Canvas很容易。一般的想法是:

var image = new Image();
image.onload = cutImageUp;
image.src = 'myimage.png';

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.push(canvas.toDataURL());
        }
    }

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

答案 2 :(得分:1)

您可以使用drawImage方法切片源图像的部分并将它们绘制到画布上:

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

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images

类似的东西:

  document.getElementById("vangogh").onclick=function()
    {
    draw();
    }; 

 function draw() {
    var ctx = document.getElementById('canvas').getContext('2d');
    ctx.drawImage(document.getElementById('source'),33,45);
                 }

然后为您的新实体创建可拖动内容:

<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>
</div>

http://www.html5rocks.com/en/tutorials/dnd/basics/