GestureMgr.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. var eventUtil = require("./event");
  2. /**
  3. * Only implements needed gestures for mobile.
  4. */
  5. var GestureMgr = function () {
  6. /**
  7. * @private
  8. * @type {Array.<Object>}
  9. */
  10. this._track = [];
  11. };
  12. GestureMgr.prototype = {
  13. constructor: GestureMgr,
  14. recognize: function (event, target, root) {
  15. this._doTrack(event, target, root);
  16. return this._recognize(event);
  17. },
  18. clear: function () {
  19. this._track.length = 0;
  20. return this;
  21. },
  22. _doTrack: function (event, target, root) {
  23. var touches = event.touches;
  24. if (!touches) {
  25. return;
  26. }
  27. var trackItem = {
  28. points: [],
  29. touches: [],
  30. target: target,
  31. event: event
  32. };
  33. for (var i = 0, len = touches.length; i < len; i++) {
  34. var touch = touches[i];
  35. var pos = eventUtil.clientToLocal(root, touch, {});
  36. trackItem.points.push([pos.zrX, pos.zrY]);
  37. trackItem.touches.push(touch);
  38. }
  39. this._track.push(trackItem);
  40. },
  41. _recognize: function (event) {
  42. for (var eventName in recognizers) {
  43. if (recognizers.hasOwnProperty(eventName)) {
  44. var gestureInfo = recognizers[eventName](this._track, event);
  45. if (gestureInfo) {
  46. return gestureInfo;
  47. }
  48. }
  49. }
  50. }
  51. };
  52. function dist(pointPair) {
  53. var dx = pointPair[1][0] - pointPair[0][0];
  54. var dy = pointPair[1][1] - pointPair[0][1];
  55. return Math.sqrt(dx * dx + dy * dy);
  56. }
  57. function center(pointPair) {
  58. return [(pointPair[0][0] + pointPair[1][0]) / 2, (pointPair[0][1] + pointPair[1][1]) / 2];
  59. }
  60. var recognizers = {
  61. pinch: function (track, event) {
  62. var trackLen = track.length;
  63. if (!trackLen) {
  64. return;
  65. }
  66. var pinchEnd = (track[trackLen - 1] || {}).points;
  67. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  68. if (pinchPre && pinchPre.length > 1 && pinchEnd && pinchEnd.length > 1) {
  69. var pinchScale = dist(pinchEnd) / dist(pinchPre);
  70. !isFinite(pinchScale) && (pinchScale = 1);
  71. event.pinchScale = pinchScale;
  72. var pinchCenter = center(pinchEnd);
  73. event.pinchX = pinchCenter[0];
  74. event.pinchY = pinchCenter[1];
  75. return {
  76. type: 'pinch',
  77. target: track[0].target,
  78. event: event
  79. };
  80. }
  81. } // Only pinch currently.
  82. };
  83. var _default = GestureMgr;
  84. module.exports = _default;