如果我理解正确:
- 你有一个 800x400 的图像,包含 20 个精灵(20 x 160x100 图像)
- 你有 20 个绝对定位的元素,它们是可拖动的
- 您想在每个元素中显示图像
是这样吗?
如果是这样,您只需要 CSS 来偏移您的背景图像。例如:
CSS
.big-image-container { position: relative; }
.big-image { background-image: url(path/to/your/image); background-repeat:no-repeat; }
.draggable-sprite { position:absolute; width: 160px; height: 100px; }
HTML
<div id="container" class="big-image-container">
</div>
JS
var spriteCountX = 5;
var spriteCountY = 4;
var container = $("#container");
var sprite, bgx, bgy;
for (var x=0; x<spriteCountX; x++) {
for (var y=0; y<spriteCountY; y++) {
sprite = $("<div>").addClass("big-image draggable-sprite")
.appendTo(container);
bgx = x * sprite.width();
bgy = y * sprite.height();
sprite.css("background-position", bgx + "px " + bgy + "px");
}
}
这样做只是抵消了每个可拖动元素内的大图像,因此它们似乎具有不同的图像作为背景。许多 JavaScript 库在他们的图标集上使用了这个技巧(例如,参见Bootstrap和jQuery UI。)
**更新**
要将可拖动图像转换为用户可以下载的大图,您需要收集每个可拖动元素的位置、大小和背景图像,并在服务器端构建它们。例如
JS
function renderCanvas() {
var imageInfo = [];
$( <draggableElementsSelector> ).each(function(i, e) {
imageInfo.push({
position: $(e).position(), // -> { top, left }
dimension: { width: $(e).width(), height: $(e).height() },
imageClass: $(e).attr("class") // .. what you need to get the bg img
});
});
$.post("url/to/script", { images: imageInfo })
.done(function(response) {
// response.imageSrc should be a link to your image for download
})
.fail(function() { alert("Image creation failed"); });
}
PHP
$imageInfo = $_POST['images'];
$imgWidth = 1; // min, just in case, cannot be 0
$imgHeight = 1; // min, just in case, cannot be 0
// first pass to find the dest image size
foreach ($imageInfo as $img) {
$imgWidth = max($imgWidth, $img->position->left + $img->dimension->width);
$imgHeight = max($imgHeight, $img->position->top + $img->dimension->height);
}
$destImage = imagecreate($imgWidth, $imgHeight); // (x, y)
foreach ($imageInfo as $img) {
$src = imagecreatefrompng( getImagePath($img->imageClass) );
imagecopymerge($destImage, $src,
$img->position->left, $img->position->top,
0, 0, $img->dimension->width, $img->dimension->height);
}
$imgFilename = generateImageFile( ... ); // whatever you need here
// Save the image to file.png
imagepng($destImage, $imgFilename);
$imgLink = convertFileToUrl( $imgFilename ); // generate downloadable link
header('Content-type: application/json');
echo json_encode(array('imageSrc' => $imgLink));
exit(); // end here