I'm trying to create a drag and drop tool using Jquery UI to drop rooms of a house into a Konva stage and then save that stage as a JSON string.
Here is the JSFiddle: http://jsfiddle.net/RossWilliams94/cxzhabgL/4/
function dragDrop(e, ui) {
// get the drop point
var x = parseInt(ui.offset.left - offsetX, 10);
var y = parseInt(ui.offset.top - offsetY, 10);
// get the drop payload (here the payload is the image)
var element = ui.draggable;
var data = element.data("url");
//var theImage = document.getElementById('bedroom');
var theImage = element.data("image");
// create a new Konva.Image at the drop point
// be sure to adjust for any border width (here border==1)
var image = new Konva.Image({
name: data,
x: x,
y: y,
image: theImage,
draggable: true
});
image.on('dblclick', function() {
image.remove();
layer.draw();
});
var $clone = ui.helper.clone();
// all clones are draggable
// if clone is shape then draggable + resizable
if (!$clone.is('.inside-droppable')) {
$(this).append($clone.addClass('inside-droppable').draggable({
containment: $stageContainer,
tolerance: 'fit',
cursor: 'pointer',
position: 'relative',
snap: true,
snapTolerance: 15
}));
if ($clone.is(".imag") === false) {
$clone.resizable({
containment: $stageContainer
});
}
$clone.on('dblclick', function () {
$clone.remove();
layer.draw();
});
$clone.css({top: y, left: x, position:'absolute'});
}
json = stage.toJSON();
group.add(image);
layer.add(group);
stage.add(layer);
}
However the problem I have run into is that as you can see from the JSFiddle when I click the save button it doesn't save the rooms dropped in from the JQuery UI only the background and label.
Is it actually possible to accomplish this? Or is it because I'm using Jquery UI with Konva which creates the problems?
Thanks.
I have fixed by problem by getting all children from the layer of type Image using var images = stage.find('Image');
Then I loop through images using images.each(function (image){};
Inside each iteration of the images in the stage I do:
var x = image.index - 2;
if (image.attrs['id'] == "sensor0") {
var imageObj = new Image();
imageObj.onload = function () {
stage.get('.sensor')[x].image(imageObj);
stage.get('.sensor')[x].draggable(false);
stage.draw();
};
imageObj.src = 'images/sensor.png';
Where it sets the correct image source to the image and make the image not draggable.
You can also add more if statements checking for the image id and setting the image source accordingly.
The problem was that when you do stage.toJSON() it doesn't record the image only attributes, you have to reload the image manually where you are redrawing the stage.
This tutorial helped: http://konvajs.github.io/docs/data_&_serialization/Complex_Load.html
Hope this helps anyone or if there are any better ways of doing this let me know!