jQuery - draggable div with zoom

孤街醉人 提交于 2019-11-29 09:47:18
tuze

You don't need to set zoom property. I just added the difference to draggable's position which occurs due to the zoom property. Hope it helps.

Fiddle

http://jsfiddle.net/TqUeS/

JS

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 get outside 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();  

    }                 
});
Yusuf Demirag

The solution above did not work out for me. So I found my own. I wanted to share it if someone else also has the same issue.

var zoom = $('#canvas').css('zoom');    
$('#dragme').draggable({
    drag: function(evt,ui)
    {
         var factor = (1 / zoom) - 1

         ui.position.top += Math.round((ui.position.top - ui.originalPosition.top) * factor)
         ui.position.left += Math.round((ui.position.left - ui.originalPosition.left) * factor)   
    }                 
});

I used both tuze's and Yusuf Demirag's solutions and added a little something for dragging on a grid:

var gridSize = 20;
$('#dragme').draggable({
    grid: [ gridSize , gridSize ],
    snap: true,
    snapTolerance: gridSize/2,

    drag: function(event,ui){
         var factor = (1 / zoom) -1;

         ui.position.top += Math.round((ui.position.top - ui.originalPosition.top) * factor);
         ui.position.top -= ui.position.top % gridSize;
         ui.position.left += Math.round((ui.position.left- ui.originalPosition.left) * factor);
         ui.position.left -= ui.position.left % gridSize;


         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();
    }
});

It has a minor bug (it can't sometimes get to an exact value eg: 160px) but it worked for what I needed.

Hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!