使用Hammer js拖动和缩放

时间:2014-02-07 18:53:01

标签: jquery css3 zoom drag hammer.js

拖动图片时遇到问题。我使用这些解决方案的组合来实现以指针为中心的压缩缩放并按我的需要工作:solution 1solution 2

当我尝试实现拖动时出现问题。我一直无法找到最佳解决方案。

这是我的代码

var scale = 1; 
var xLast = 0; 
var yLast = 0; 
var xImage = 0; 
var yImage = 0;
var lastScale, xNew, yNew;        
Hammer($('#myImage').get(0)).on("touch drag transform", function (event) {
    switch(event.type) {
        case 'touch':
             lastScale = scale;
             break;
        case 'drag':
             var posX = event.gesture.deltaX;
             var posY = event.gesture.deltaY;

             var xScreen = posX; //- $(this).offset().left;
             var yScreen = posY; //- $(this).offset().top;
             xImage = xImage + ((xScreen - xLast) / scale);
             yImage = yImage + ((yScreen - yLast) / scale);

             xNew = (xScreen - xImage) / scale;
             yNew = (yScreen - yImage) / scale;

             xLast = xScreen;
             yLast = yScreen;

             break;
        case 'transform':
             var posiX = event.gesture.center.pageX;
             var posiY = event.gesture.center.pageY;

             var xScreen = posiX; //- $(this).offset().left;
             var yScreen = posiY; //- $(this).offset().top;

             xImage = xImage + ((xScreen - xLast) / scale);
             yImage = yImage + ((yScreen - yLast) / scale);

             scale = Math.max(0, Math.min(lastScale * event.gesture.scale, 10));

             xNew = (xScreen - xImage) / scale;
             yNew = (yScreen - yImage) / scale;

             xLast = xScreen;
             yLast = yScreen;                     

             break;                
        }             
   $(this).css('-webkit-transform', 'scale(' + scale + ')' + 'translate(' + xNew + 'px, ' + yNew + 'px' + ')')
                    .css('-webkit-transform-origin', xImage + 'px ' + yImage + 'px')
                    .css('-moz-transform', 'scale(' + scale + ') translate(' + xNew + 'px, ' + yNew + 'px)')
                    .css('-moz-transform-origin', xImage + 'px ' + yImage + 'px')
                    .css('-o-transform', 'scale(' + scale + ') translate(' + xNew + 'px, ' + yNew + 'px)')
                    .css('-o-transform-origin', xImage + 'px ' + yImage + 'px')
                    .css('transform', 'scale(' + scale + ') translate(' + xNew + 'px, ' + yNew + 'px)');      
        });

请,我需要帮助来实现拖动。任何建议,想法,解释和实施都很受欢迎。

感谢。

PD。抱歉我的英语不好。

1 个答案:

答案 0 :(得分:0)

这适用于我的拖动开关语句:

     posX = ev.gesture.deltaX + lastX;
     posY = ev.gesture.deltaY + lastY;
     break;

然后此代码应该适用于转换:

"translate3d(" + posX + "px," + posY + "px, 0) ";