Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Fix broken TouchEvents. Tested on iPhone, iPad, iPod and Android.

  • Loading branch information...
commit 0d3626a3f225db0e644bef1726198f9cf8816389 1 parent 26ce6d0
@smindel authored
Showing with 61 additions and 4 deletions.
  1. +33 −4 src/controls.js
  2. +28 −0 tests/touchevents.html
View
37 src/controls.js
@@ -25,6 +25,7 @@ Crafty.extend({
mouseDispatch: function (e) {
if (!Crafty.mouseObjs) return;
+ if(window.TouchEvent && e instanceof TouchEvent) { this._mockMouseEvent(e); return; }
Crafty.lastEvent = e;
var maxz = -1,
@@ -37,10 +38,6 @@ Crafty.extend({
tar = e.target ? e.target : e.srcElement,
type = e.type;
- if (type === "touchstart") type = "mousedown";
- else if (type === "touchmove") type = "mousemove";
- else if (type === "touchend") type = "mouseup";
-
//Normalize button according to http://unixpapa.com/js/mouse.html
if (e.which == null) {
e.mouseButton = (e.button < 2) ? Crafty.mouseButtons.LEFT : ((e.button == 4) ? Crafty.mouseButtons.MIDDLE : Crafty.mouseButtons.RIGHT);
@@ -137,6 +134,38 @@ Crafty.extend({
/**@
+ * #Crafty._mockMouseEvent
+ * @category Input
+ * TouchEvents have a different structure then MouseEvents.
+ * The relevant data lives in e.changedTouches[0].
+ * To normalize TouchEvents we catch em and dispatch a mock MouseEvent instead.
+ * @see Crafty.mouseDispatch
+ */
+
+ _mockMouseEvent: function(e) {
+
+ var type;
+ if (e.type === "touchstart") type = "mousedown";
+ else if (e.type === "touchmove") type = "mousemove";
+ else if (e.type === "touchend") type = "mouseup";
+
+ var touch = e.changedTouches[0];
+
+ var mockup = document.createEvent("MouseEvents");
+ mockup.initMouseEvent(type, true, true, window, 0,
+ touch.screenX,
+ touch.screenY,
+ touch.clientX,
+ touch.clientY,
+ false, false, false, false, 0, e.target
+ );
+ mockup.target = e.target;
+
+ e.target.dispatchEvent(mockup);
+ },
+
+
+ /**@
* #KeyboardEvent
* @category Input
* Keyboard Event triggerd by Crafty Core
View
28 tests/touchevents.html
@@ -0,0 +1,28 @@
+<html>
+<head>
+ <script type="text/javascript" src="../crafty-local.js"></script>
+ <style>
+ #cr-stage {
+ background-color: grey;
+ }
+ </style>
+</head>
+<body>
+</body>
+<script type="text/javascript">
+ Crafty.init(200, 200);
+ Crafty.c("Test", {
+ init: function() {
+ this.requires('2D, DOM, Color, Mouse, Draggable');
+ },
+ });
+
+ Crafty.scene('main', function() {
+ Crafty.e("Test")
+ .attr({x: 100, y: 100, w:100, h:100})
+ .color('red');
+ });
+
+ Crafty.scene('main');
+</script>
+</html>
Please sign in to comment.
Something went wrong with that request. Please try again.