Reputation: 33
I am placing an image on the canvas using drap & drop but the problem is, after dropping the image on canvas, image is loosing it's original position where it is dropped.
Sometimes it comes down from the original position and sometimes moves to right. Here is the code:
$("#draggable1").draggable({
stop: function(event, ui)
{
var canv = document.getElementById("tools_sketch");
var rect = canv.getBoundingClientRect();
x = event.clientX - rect.left;
y = event.clientY - rect.top;
ans = confirm("Is it correct position?");
if (ans)
{
dropimg_over_ground("img1", x, y);
$('#draggable1').remove();
}
}
});
dropimg_over_ground = function(imgid, lefti, topi)
{
var c = document.getElementById("tools_sketch");
var ctx = c.getContext("2d");
var img = document.getElementById(imgid);
ctx.drawImage(img, lefti, topi);
}
I have searched forum alot and tried many solutions but it's not worked.
Upvotes: 2
Views: 1442
Reputation: 791
Just subtract the offset of the container:
$('#drag').draggable({
stop: function(e, ui){
console.log('drag');
console.log($(this).offset().top - $('#canvas').offset().top)
console.log($(this).offset().left - $('#canvas').offset().left)
}
});
$("#canvas").droppable({
accept: "#drag",
drop: function (event, ui) {
},
out: function (event, ui) {
console.log('dragged out');
}
});
Working example, http://jsfiddle.net/kBM6u/6/
check the console for the results
Regards
Upvotes: 4