通过Javascript将图像切割成碎片

Cutting an Image into pieces through Javascript

本文关键字:碎片 图像 Javascript 通过      更新时间:2023-09-26

我正在创建一个简单的拼图。为了做到这一点,我需要把我正在使用的图片剪成20块。在Javascript中有没有一种方法可以将一张图片切成20个相等的部分,并将其保存为网页中的20个不同对象?还是我只需要进入photoshop,自己剪下每一张照片,然后把它叫进来?

使用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];
}

您可以将图像设置为div上的背景,然后设置其背景位置。这与使用CSS精灵基本相同。

(假设碎片为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
}

您可以使用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/