I'm facing an issue while dragging the elements inside canvas, here my canvas is div. Inside a div I have two draggable elements. I just applied a zoom property for those draggable elements. I would have applied the zoom for a parent div but based on the requirement I should apply zoom only for the draggable element. However after applying the zoom for the draggable elements it's not responding well, when I try to move it to the edge(both X & Y) of the canvas. I tried some calculation but it's working.
var zoom = $('#canvas').css('zoom');
var canvasHeight = $('#canvas').height();
var canvasWidth = $('#canvas').width();
$('#dragme').draggable({
drag: function(evt,ui)
{
// zoom fix
// ui.position.top = Math.round(ui.position.top / zoom);
// ui.position.left = Math.round(ui.position.left / zoom);
// don't let draggable to get outside of the canvas
if (ui.position.left < 0)
ui.position.left = 0;
if (ui.position.left + $(this).width() > canvasWidth)
ui.position.left = canvasWidth - $(this).width();
if (ui.position.top < 0)
ui.position.top = 0;
if (ui.position.top + $(this).height() > canvasHeight)
ui.position.top = canvasHeight - $(this).height();
}
});
$('#dragme1').draggable({
drag: function(evt,ui)
{
// zoom fix
// ui.position.top = Math.round(ui.position.top / zoom);
//ui.position.left = Math.round(ui.position.left / zoom);
// don't let draggable to get outside of the canvas
if (ui.position.left < 0)
ui.position.left = 0;
if (ui.position.left + $(this).width() > canvasWidth)
ui.position.left = canvasWidth - $(this).width();
if (ui.position.top < 0)
ui.position.top = 0;
if (ui.position.top + $(this).height() > canvasHeight)
ui.position.top = canvasHeight - $(this).height();
}
});
#canvas {
width:500px;
height:250px;
border:1px solid #444;
}
#dragme {
width:100px;
height:50px;
background:#f30;
zoom:0.8;
}
#dragme1 {
width:100px;
height:50px;
background:blue;
zoom:0.8;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<div id="canvas">
<div id="dragme"></div>
<div id="dragme1"></div>
</div>