If I understand this correctly :
- You have a 800x400 image with 20 sprites (20 x 160x100 images)
- You have 20 absolute positionned elements, which are draggable
- You want to display the images in each element
Is that it?
If so, you simply need CSS to offset your background image. For example:
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");
}
}
What this does is simply offset the big image inside each draggable elements so they seem to have different images as background. Many JavaScript libraries uses this trick for their icon set (see Bootstrap and jQuery UI for example.)
** Update **
To convert the draggable images into a big image that users can download, you'll need to collect the position, sizes and background images of each draggable elements and construct them server side. For example
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