The*_*s44 18 html javascript html5
我正在创建一个简单的拼图游戏.为了做到这一点,我需要将我使用的图片切成20块.有没有办法在Javascript中将图片分割成20个相等的部分,并将它们保存为网页中的20个不同的对象?或者我是否只需要进入photoshop并自己剪切每张照片并将其调用?
Mat*_*eer 22
这对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];
}
Run Code Online (Sandbox Code Playgroud)
Dio*_*ane 20
您可以通过将图像设置为div上的背景,然后设置其背景位置来完成此操作.这与使用CSS Sprites基本相同.
(假设件数为100 x 100px)
<div class="puzzle piece1"></div>
<div class="puzzle piece2"></div>
Run Code Online (Sandbox Code Playgroud)
CSS:
.puzzle {
background-image:url(/images/puzzle.jpg);
width:100px;
height:100px;
}
.piece1 {
background-position:0 0
}
.piece2 {
background-position:-100px -100px
}
Run Code Online (Sandbox Code Playgroud)