如何使用Javascript在Safari中访问iPhone的新3D触控?

时间:2015-12-01 21:13:56

标签: javascript ios iphone safari 3dtouch

Apple宣布推出全新iPhone 6S和6S +,users can now use pressure to interact with their apps。是否有一个JavaScript API供Web开发人员在标准网站上利用这一新功能?如果是这样,它如何实施?

2 个答案:

答案 0 :(得分:2)

是的,根据W3C,a new force property has been recently added to the spec of the Touch interface,范围从0(最小力)到1(最大力)。这已经适用于iOS9上的Safari(不确定Chrome或其他浏览器是否已实现它)。

快速回答:

要访问此属性,只需调用

即可
touchForce = evt.originalEvent.touches[0].force;

touchstarttouchmove事件监听器中。

此实施存在一些问题:

  • touchstart上,力量将非常接近0,因为一旦检测到第一个压力迹象就会调用它。
  • 如果压力增加或减少,touchstart事件将不会再次发射。
  • touchmove不可靠,因为在阅读新的force之前,您必须等待位置更改,但情况并非总是如此。

<强>解决方案:

要解决此问题,您可以设置一个超时,在touchstart后每隔几毫秒计算一次此力,然后清除touchend上的超时。

var tO = 0;
$("#div1").on("touchstart", startTouch);
$("#div1").on("touchend", endTouch);

function startTouch(evt){
    evt.preventDefault();
    touchForce = evt.originalEvent.touches[0].force;
    tO = window.setTimeout(function(){startTouch(evt)}, 100);
    // Do something with touchForce
}

function endTouch(){
    touchForce = 0;
    window.clearTimeout(tO);
    // Do something else
}

Try it out in this CodePen I created

有点hacky,但它确实有效。也许将来他们会创建一个新的forcechange事件,但这就是我们现在所拥有的。

请原谅JQuery,我用它来更快地说明这一点。

答案 1 :(得分:0)

您可以使用JS库Pressure.js。如果你有iPhone 6s或带有新Force Touch触控板的新Macbook,它可以很容易地在iOS和OSX上获得Force和3D Touch值。

语法也很简单,这是一个例子:

Pressure.set('#element', {
  start: function(){
    // this is called on force start
  },
  end: function(){
    // this is called on force end
  },
  startDeepPress: function(){
    // this is called on "force click" / "deep press", aka once the force is greater than 0.5
  },
  endDeepPress: function(){
    // this is called when the "force click" / "deep press" end
  },
  change: function(force, event){
    // this is called every time there is a change in pressure
    // here the 'force' variable passed in container the current pressure force
  },
  unsupported: function(){
    // this is called once there is a touch on the element and the device or browser does not support Force or 3D touch
  }
});