使用gesturechange和gestureend实现JavaScript缩放和旋转

19

我正在处理一些触摸事件和手势,我希望能够缩放和旋转对象,我已经成功地使其可拖动,但手势仍然让我感到困扰。手势是在起作用,但它们是不流畅的,每当你用手指捏合变焦或尝试旋转时,它会从一个手指跳到另一个手指。

以下是我的参考代码。

var width = 300; var height = 300; var rotation = 0;
$('.dynamic').live("gesturechange gestureend", function(e){
var orig = e.originalEvent;

if(e.type == 'gesturechange'){
    e.preventDefault();
    $(this).css("width", parseFloat(width) * orig.scale);
    $(this).css("height", parseFloat(height) * orig.scale);
    $(this).css("-webkit-transform","rotate(" + ((parseFloat(rotation) + orig.rotation) % 360) + "deg)");
}else if(e.type == 'gestureend'){
    a.w[ids] = parseFloat(width) * orig.scale;
    a.h[ids] = parseFloat(height) * orig.scale;
    a.rotation[ids] = (parseFloat(rotation) + orig.rotation) % 360;
}
});
有没有什么方法可以使它更加平滑,并防止它从手指上跳动,或者我采取的方法错了。需要一些技巧和帮助。
找到解决方案。
似乎我的拖动触摸事件干扰了手势,这就是为什么它一直从一个手指跳到另一个手指的原因,解决方法是不使用手势,而是计算对象上的触摸次数,使用touch start、end和change代替手势。
这是代码:
var touches = 0; var width = 300; var height = 300; var rotation = 0;
$('.dynamic').live("touchstart touchmove touchend", function(e){
var orig = e.originalEvent;   

if(e.type == 'touchstart'){
 if(orig.touches.length == 1){
    touches = 1; 
 }else if(orig.touches.length == 2){
    touches = 2;
 }
}else if(e.type == 'touchmove'){
 e.preventDefault();
 if(touches == 2){
        $(this).css("width", parseFloat(width) * orig.scale);
        $(this).css("height", parseFloat(height) * orig.scale);
        $(this).css("-webkit-transform","rotate(" + ((parseFloat(rotation) + orig.rotation) % 360) + "deg)");
 }
}else if(e.type == 'touchend'){
    if(touches == 2){
        a.w[ids] = parseFloat(width) * orig.scale;
        a.h[ids] = parseFloat(height) * orig.scale;
        a.rotation[ids] = (parseFloat(rotation) + orig.rotation) % 360;
    }
}
});

3
非常感谢您发布答案!通常的做法是将它作为答案发布,而不是将其编辑到问题中。(自己回答问题并没有什么不妥。) - RichieHindle
由于我在这里是新手,所以暂时无法回答。 - ryuutatsuo
你的第一种方法在Android 2.x上可行吗?我想支持捏合手势,但第二种方法(细粒度触摸支持)只适用于iOS(和Android 3.0 / 平板电脑以及WebOS?)。感谢您发布您的解决方案! - Chris Bosco
将高度和宽度更改为比例变换也可以使结果更加平滑。 - Chris Bosco
据我所知,触摸事件对象没有比手势事件对象更具有规模属性。您如何获得它? - BairDev
2个回答

10

你的解决方案能够工作,但不是最优雅的:你仍然可以使用第一段代码,并依赖于gesture事件。
你需要做的就是确保touch事件处理程序不会干扰你的gesture事件处理程序。
只需将以下内容添加到touch事件处理程序中:

$('.dynamic').live("touchstart touchmove touchend", function(e){
    if(e.originalEvent.touches.length > 1)
        return;
    /* your touch code here */
});

然后使用你现有的手势代码:

$('.dynamic').live("gesturechange gestureend", function(e){
     /* your gesture code here */
});

这应该有效,因为手势事件仅在屏幕有两个或更多手指触摸时才会触发,并且当此情况发生时没有其他代码执行,因为触摸事件处理程序仅响应单个触摸。


0

或许 jQuery 并不是这个任务的最佳选择。你可以考虑使用 Sencha Touch。它已经非常好地实现了你想要的功能。看一下演示。根据你想要做什么,jQuery Mobile 也是一个不错的选择。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接